我正在制作一个接受 10 个字符串并将它们发送到文本文件的程序。但是,我的问题是它只是覆盖文件中存在的任何先前值。有什么想法如何防止它被覆盖吗? 我的程序如下:
import java.io.*;
public class TEST
{
public static void main(String args[])throws IOException
{
InputStreamReader read=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(read);
int a;
String x;
for (a=1; a<=10; a++)
{
System.out.println("Please enter a word.");
x=in.readLine();
PrintStream konsole = System.out;
System.setOut(new PrintStream("TEST.txt"));
System.out.println(x);
System.setOut(konsole);
}
System.out.println("DONE");
}
}
最佳答案
尝试写入输出流(不是重定向的 System.out)。
使用FileOutputStreams
,您可以选择是否要追加到文件或写入新文件(构造函数中的 boolean 值,请查看 JavaDoc)。
尝试使用此代码创建一个文件的输出流,该输出流不会覆盖该文件,而是附加到该文件。
OutputStream out = new FileOutputStream(new File("Test.txt"), true);
还要确保您不是在循环的每次迭代中创建 Stream,而是在循环开始时创建 Stream。
如果您在循环之后也关闭了输出流(在finally block 中),那么应该没问题。
关于java - 程序进行覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19955143/