Java文件 – 打开文件并写入

我知道我们应该在我们的问题中添加一些代码,但我真的很傻眼,不能包裹我的头脑或找到任何可以遵循的例子。

基本上我想打开文件C:\ A.txt ,其中已经包含内容,并在结尾处写一个字符串。 基本上就是这样。

文件A.txt包含:

John Bob Larry 

我想打开它并在结尾写Sue所以文件现在包含:

 John Bob Larry Sue 

很抱歉没有代码示例,今天早上我的大脑已经死了……

请搜索由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(); } } 

建议:

  • 创建一个File对象,该对象引用磁盘上现有的文件。
  • 使用FileWriter对象,并使用带有File对象和布尔值的构造函数,后者如果为true允许将文本附加到文件中(如果存在)。
  • 然后将传递FileWriter的PrintWriter初始化为其构造函数。
  • 然后在PrintWriter上调用println(...) ,将新文本写入文件。
  • 与往常一样,完成后关闭资源(PrintWriter)。
  • 与往常一样,不要忽略exception,而是捕获并处理它们。
  • PrintWriter的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(); } } 

容易,不是吗?

为了扩展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(); } 

不要说我们对你不好!