我正在创建一个接受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");
}
}
答案 0 :(得分:1)
尝试写入输出流(不是重定向的System.out
)。
使用FileOutputStreams
,您可以选择是要附加到文件还是写入新文件(构造函数中的布尔值,请查看JavaDoc)。
尝试使用此代码创建一个文件的输出流,该文件不会覆盖该文件,但会附加到该文件中。
OutputStream out = new FileOutputStream(new File("Test.txt"), true);
另外,请确保在循环的每次迭代中都不创建Stream,但是在循环开始时。
如果你在循环之后关闭输出流(在finally块中),那么你应该没问题。
答案 1 :(得分:0)
这应该适合你:
public static void main(String[] args) throws IOException {
InputStreamReader read=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(read);
OutputStream out = new FileOutputStream(new File("TEST.txt"), true);
for (int a=1; a<=10; a++)
{
System.out.println("Please enter a word.");
out.write(in.readLine().getBytes());
out.write(System.lineSeparator().getBytes());
}
out.close();
System.out.println("DONE");
}