【问题标题】:Write problem - lossing the original data写入问题 - 丢失原始数据
【发布时间】:2010-11-19 00:16:06
【问题描述】:

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

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

}

【问题讨论】:

    标签: java file-io append


    【解决方案1】:

    【讨论】:

      【解决方案2】:

      您需要以附加模式打开myFile。示例见this link

      【讨论】:

        【解决方案3】:

        我们已经为您提供:new Formatter(myFile);,您会想使用new Formatter(new FileWriter(myfile, true)。 true 表示您要附加到该文件。

        【讨论】:

          【解决方案4】:

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

          这段代码可以用默认的平台编码写入数据:

            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 上产生不同的输出时,上述方法可以lose data

          需要注意的一种情况是编码插入了byte order mark。如果您想在标有 little-endian BOM 的 UTF-16 中编写无损 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();
            }
          }
          

          支持的编码:

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-11-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-09
            相关资源
            最近更新 更多