2012-05-19 40 views
14

我知道我们应该在我们的问题中添加一段代码,但是我非常傻眼,无法包住我的头或找不到任何示例。Java文件 - 打开文件并写入它

基本上我想打开文件C:\ A.txt,它已经有了内容,并在最后写入一个字符串。基本上就是这样。

文件a.txt中包含:

John 
Bob 
Larry 

我想打开它,并在最后写苏所以文件现在包含:

John 
Bob 
Larry 
Sue 

对不起,没有代码示例,我的大脑死者今天早上....

+13

哦这篇文章是在极客和戳! http://geek-and-poke.com/geekandpoke/2013/11/10/indirection – Lai

回答

32

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

我首先查了一下Google,然后把它带到这里;) – Josh

11

建议:

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

容易,不是吗?

3

要在鳗鱼先生评论扩展,你可以做这样的:

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(); 
    } 

不要说我们不好哦!

+3

1+到ya,但不要忘记在finally块中关闭打印机,而不是在try块中。你不想要任何悬而未决的资源。看我的例子,看看我的意思。 –