如何编写文本文件Java?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (20)

下面的代码不会生成一个文件(我在任何地方都看不到该文件?

try {
    //create a temporary file
    String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(
        Calendar.getInstance().getTime());
    File logFile=new File(timeLog);

    BufferedWriter writer = new BufferedWriter(new FileWriter(logFile));
    writer.write (string);

    //Close writer
    writer.close();
} catch(Exception e) {
    e.printStackTrace();
}
提问于
用户回答回答于

可以尝试下这个:

public class TestWriteFile {

    public static void main(String[] args) {
        BufferedWriter writer = null;
        try {
            //create a temporary file
            String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
            File logFile = new File(timeLog);

            // This will output the full path where the file will be written to...
            System.out.println(logFile.getCanonicalPath());

            writer = new BufferedWriter(new FileWriter(logFile));
            writer.write("Hello world!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // Close the writer regardless of what happens...
                writer.close();
            } catch (Exception e) {
            }
        }
    }
}

还请注意,您的示例将覆盖所有现有文件。如果要将文本附加到文件中,则应执行以下操作:

writer = new BufferedWriter(new FileWriter(logFile, true));
用户回答回答于

想在MadProgrammer的回答中多加一点。

在多行写入的情况下,执行命令时

writer.write(string);

可能会注意到

System.out.println("\n");

因此,整个文本作为一个大块的文本,在大多数情况下是不可取的

String newline = System.getProperty("line.separator");

扫码关注云+社区