【问题标题】:how to save a file exactly as it is from a String java [duplicate]如何从String java中完全保存文件[重复]
【发布时间】:2016-11-22 19:57:40
【问题描述】:

例如,假设我有以下字符串,

String str = "Patient: " + patient +
"\nMonth: " + month +
"\nDay : " + day +
"\nYear: " + year 
+"\nDescription: " + description;

//And I write this data to a file, 
PrintWriter outputFile = new PrintWriter("hello.txt");

outputFile.println(str);

然后文件上的结果只有一行,当我打开它时, 有没有办法,只做格式作为传递到文件的字符串。?

提前谢谢你。

【问题讨论】:

  • 你在 Windows 上,不是 'cha?

标签: java string file


【解决方案1】:

\n 在 UNIX 上按预期工作。使用 Windows 可能需要 \r\n。请查看https://softwareengineering.stackexchange.com/questions/29075/difference-between-n-and-r-n

【讨论】:

    【解决方案2】:

    它对我有用,就像在 Linux 系统上编写的一样。如果您使用的是 Windows 机器,请尝试将“\r\n”作为换行符,而不仅仅是“\n”。还有一个好习惯是在打开 PrintWriter 时指定编码。理想情况下,您可以使用 System.getProperty("line.separator") 来获取平台相关的行分隔符。

    String lineSeparator = System.getProperty("line.separator");
    String str = "Patient: " + "a" +
                lineSeparator + "Month: " + "a" +
                lineSeparator + "Day : " + "a" +
                lineSeparator + "Year: " + "a"
                lineSeparator + "Description: " + "a";
    
        try {
            PrintWriter outputFile = new PrintWriter("hello.txt", "UTF-8");
            outputFile.println(str);
            outputFile.close();
            System.out.println("writing file");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-09
      • 1970-01-01
      • 2016-02-05
      • 1970-01-01
      • 2014-10-25
      • 1970-01-01
      • 2018-07-25
      相关资源
      最近更新 更多