我知道我们应该在我们的问题中添加一段代码,但是我非常傻眼,无法包住我的头或找不到任何示例。Java文件 - 打开文件并写入它
基本上我想打开文件C:\ A.txt,它已经有了内容,并在最后写入一个字符串。基本上就是这样。
文件a.txt中包含:
John
Bob
Larry
我想打开它,并在最后写苏所以文件现在包含:
John
Bob
Larry
Sue
对不起,没有代码示例,我的大脑死者今天早上....
我知道我们应该在我们的问题中添加一段代码,但是我非常傻眼,无法包住我的头或找不到任何示例。Java文件 - 打开文件并写入它
基本上我想打开文件C:\ A.txt,它已经有了内容,并在最后写入一个字符串。基本上就是这样。
文件a.txt中包含:
John
Bob
Larry
我想打开它,并在最后写苏所以文件现在包含:
John
Bob
Larry
Sue
对不起,没有代码示例,我的大脑死者今天早上....
请搜索Google由拉里佩奇和谢尔盖布林给世界。
BufferedWriter out = null;
try
{
FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
out = new BufferedWriter(fstream);
out.write("\nsue");
}
catch (IOException e)
{
System.err.println("Error: " + e.getMessage());
}
finally
{
if(out != null) {
out.close();
}
}
我首先查了一下Google,然后把它带到这里;) – Josh
建议:
true
允许将文本附加到文件中(如果存在)。println(...)
,将新文本写入文件。close()
应位于try的finally块中。例如,
PrintWriter pw = null;
try {
File file = new File("fubars.txt");
FileWriter fw = new FileWriter(file, true);
pw = new PrintWriter(fw);
pw.println("Fubars rule!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (pw != null) {
pw.close();
}
}
容易,不是吗?
要在鳗鱼先生评论扩展,你可以做这样的:
File file = new File("C:\\A.txt");
FileWriter writer;
try {
writer = new FileWriter(file, true);
PrintWriter printer = new PrintWriter(writer);
printer.append("Sue");
printer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
不要说我们不好哦!
1+到ya,但不要忘记在finally块中关闭打印机,而不是在try块中。你不想要任何悬而未决的资源。看我的例子,看看我的意思。 –
哦这篇文章是在极客和戳! http://geek-and-poke.com/geekandpoke/2013/11/10/indirection – Lai