我知道我们应该在我们的问题中添加一段代码,但我非常傻眼,无法包裹我的头脑或找到任何可以遵循的例子。
基本上我想打开文件 C:\ A.txt ,其中已有内容,并在结尾处写一个字符串。基本上是这样的。
文件A.txt包含:
John
Bob
Larry
我想打开它并在结尾写Sue,所以文件现在包含:
John
Bob
Larry
Sue
很抱歉没有代码示例,今天早上我的大脑已经死了......
答案 0 :(得分:34)
请搜索Larry Page和Sergey Brin给世界的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();
}
}
答案 1 :(得分:11)
建议:
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();
}
}
容易,不是吗?
答案 2 :(得分:3)
为了扩展Eels先生的评论,你可以这样做:
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();
}
不要说我们对你不好!