0

每次写入文本文件都会丢失原始数据,如何读取文件并将数据输入到空行或下一行是空的?

public void writeToFile()
{   

    try
    {
        output = new Formatter(myFile);
    }
    catch(SecurityException securityException)
    {
        System.err.println("Error creating file");
        System.exit(1);
    }
    catch(FileNotFoundException fileNotFoundException)
    {
        System.err.println("Error creating file");
        System.exit(1);
    }

    Scanner scanner = new Scanner (System.in);

    String number = "";
    String name = "";

    System.out.println("Please enter number:");
    number = scanner.next();

    System.out.println("Please enter name:");
    name = scanner.next();

    output.format("%s,%s \r\n",  number, name);
    output.close();

}
4

4 回答 4

3

您必须打开文件进行追加

于 2009-08-12T15:33:51.523 回答
1

您需要以myFile附加模式打开。有关示例,请参见此链接。

于 2009-08-12T15:33:59.603 回答
1

正如其他人所说,使用附加选项。

此代码可以使用默认平台编码写入数据:

  private static void appendToFile() throws IOException {
    boolean append = true;
    OutputStream out = new FileOutputStream("TextAppend.txt", append);
    Closeable resource = out;
    try {
      PrintWriter pw = new PrintWriter(out);
      resource = pw;
      pw.format("%s,%s %n", "foo", "bar");
    } finally {
      resource.close();
    }
  }

有许多类可以围绕OutputStream来实现相同的效果。请注意,当代码在不使用 Unicode 默认编码的平台(如 Windows)上运行时,上述方法可能会丢失数据,并且可能在不同的 PC 上产生不同的输出。

需要注意的一种情况是编码是否插入了字节顺序标记。如果您想编写UTF-16带有 little-endian BOM 标记的无损 Unicode 文本,则需要检查文件中的现有数据。

private static void appendUtf16ToFile() throws IOException {
  File file = new File("TextAppend_utf16le.txt");
  String encoding = (file.isFile() && file.length() > 0) ?
      "UnicodeLittleUnmarked" : "UnicodeLittle";
  boolean append = true;
  OutputStream out = new FileOutputStream(file, append);
  Closeable resource = out;
  try {
    Writer writer = new OutputStreamWriter(out, encoding);
    resource = writer;
    PrintWriter pw = new PrintWriter(writer);
    resource = pw;
    pw.format("%s,%s %n", "foo", "bar");
  } finally {
    resource.close();
  }
}

支持的编码:

于 2009-08-12T18:07:49.623 回答
0

我们就是你:new Formatter(myFile);你会想要使用new Formatter(new FileWriter(myfile, true). true 表示您要附加到该文件。

于 2009-08-12T15:35:57.510 回答