gpt4 book ai didi

java - 如何使用 Printwriter 将字符串数组写入 java 中的文本文件?

转载 作者:行者123 更新时间:2023-12-02 04:44:51 26 4
gpt4 key购买 nike

我需要帮助使用 Printwriter 将数组对象的一些内容(以下是我正在使用的数组的两个示例)写入文本文件。有任何想法吗?我是初学者,所以越简单越好,谢谢!

Astronauts[0][0] = new Passengers(-1, "", 1, 0, 0, "", "", 0, "", "", "", "", ""); 

Astronauts[0][1] = new Passengers(0, "Pilot", 2424, 14, 0, "Bruce", "Banner", 0, "678-884-6325", "Mom", "678-884-6323","","");

Astronauts[0][2] = new Passengers(0, "Pilot", 1248, 3, 0, "Sally", "Forth", 0, "678-921-1135", "Hannah", "678-921-1130","","");


Astronauts[1][0] = new Passengers(-1, "", 2, 0, 0, "", "", 0, "", "", "", "", "");

Astronauts[1][1] = new Passengers(0, "Pilot", 1022, 55, 0, "Buz", "Aldrin", 0, "404-014-4553", "June", "404-014-4555","","");

Astronauts[1][2] = new Passengers(0, "Pilot", 2813, 8, 0, "Alice", "Dyer", 0, "678-884-6325", "Mom", "678-884-6323","","");

最佳答案

我不确定我是否正确地捕获了您的问题,因为将数组的内容写入文件非常简单:

String[] arr = {"a", "b", "c"};
try {
PrintWriter pw = new PrintWriter(new FileWriter("output.txt"));
pw.println(Arrays.toString(arr));
pw.flush();
System.out.println("Finished");
} catch (IOException e) {
e.printStackTrace();
}

[编辑]

我意识到我可能没有解决您的整个问题。如果您想知道如何编写数组中包含的对象的所需特征,您可以覆盖 toString()您的自定义类的方法:

class A {
public static void main(String[] args) {
B[] bs = {new B("a", "b"),
new B("c", "d"),
new B("e", "f"),
new B("g", "h")};

try {
PrintWriter pw = new PrintWriter(new FileWriter("output.txt"));
for (B b : bs) {
pw.println(b);
}
pw.flush();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Finished");
}
}

class B {
private String prop1;
private String prop2;

public B (String prop1, String prop2) {
this.prop1 = prop1;
this.prop2 = prop2;
}

@Override
public String toString() {
return this.prop1 + " " + this.prop2;
}
}

关于java - 如何使用 Printwriter 将字符串数组写入 java 中的文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29750678/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com