Java文件 - 打开文件并写入它

时间:2012-05-19 18:16:08

标签: java file

我知道我们应该在我们的问题中添加一段代码,但我非常傻眼,无法包裹我的头脑或找到任何可以遵循的例子。

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

文件A.txt包含:

John
Bob
Larry

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

John
Bob
Larry
Sue

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

3 个答案:

答案 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)

建议:

  • 创建一个引用磁盘上现有文件的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();
     }
  }

容易,不是吗?

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

不要说我们对你不好!