2014-01-14 154 views
-1
BufferedReader input = new BufferedReader (new FileReader("data.txt")); //Reading the file 
String data [] = readFile (input); //data is each line in the file 
String student [] = new String [10]; 
for(int x = 0; x<data.length; x++) 
    {     
    student = data[x].split(","); //each line is being split into 11 parts 
    } 

我需要写入此文件而不覆盖它。我问10个问题,如“你的名字是什么?”和“你的姓氏是什么?”。我需要这些问题的答案进入学生[]。就像我说的,我需要代码写入这个文件而不覆盖它。如何在不覆盖java的情况下写入文件?

+1

我看到在这个代码输入,但没有输出。你打算如何在没有任何输出的情况下写入文件? – Tdorno

+0

您可以*追加*(关键字)到文件而不覆盖它。 – user2864740

+0

我认为“追加”是你正在寻找的单词,它需要在特定模式下打开文件,并观察一些关于如何引用它的限制。 –

回答

2
PrintWriter out = null; 
try { 

out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", 

true))); 
    out.println("the text"); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
finally { 
    if (out != null) { 
    out.close(); 
    } 
} 

FileWriter构造函数的第二个参数会告诉它追加到文件(而不是清除文件)。

+2

+1请在finally中使用'try-with-resources'或'close()',永远不要空抓catch'做一些日志或类似的东西:) – nachokk

+0

@nachokk你是绝对正确的,我抄的SO代码是只是粘贴而不改变。我修改了答案。 –

+1

*“我抄录的SO代码”* ...您的意思是,其他人的回答是否应该被标记为dup? –

相关问题