gpt4 book ai didi

java - 使用 Java 序列化 I/O

转载 作者:行者123 更新时间:2023-11-30 07:19:51 25 4
gpt4 key购买 nike

所以最近我一直在此处发布有关 Java 的类似问题。每次有人回答我的问题时,都会出现更多问题。谢谢大家。解决了追加问题,现在一切都变得漂亮了。

[文件.java]

public class File {

public static void main(String[] args) {

FileWrite fW = new FileWrite();

try (BufferedReader br = new BufferedReader(new FileReader("B:\\LongIn.dat"))) {
String stCurrent;
while ((stCurrent = br.readLine()) != null) {
System.out.println(stCurrent);
fW.serializeAddress(stCurrent);
}
} catch (IOException e) {
e.printStackTrace();
}

}
}

[文件写入.java]

public class FileWrite {

public void serializeAddress(String in) {
try {
File file = new File("B:\\LongOut.txt");
if (!file.exists()) {
file.createNewFile();
}

FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(in);

bw.close();

System.out.println("Done");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

现在我的程序在将字符串写入文件时追加。但是我有两个问题。

  1. 在阅读方面,将大量字符串存入某个变量以便我的程序可以使用它的好方法是什么?

  2. 追加输出有效,但组织得不好。与此一样,结果在输出文件中相互啮合。如何使输出全部对齐并看起来不错?

最佳答案

如果您想要分隔行,最简单的做法是在 write() 之后添加 newLine() 调用,而无需更改太多代码,如下所示:

bw.write(in);
bw.newLine();
bw.close();

Java文档:BufferedWriter#newLine()

关于java - 使用 Java 序列化 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14357298/

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