【问题标题】:Newlines in string not passing out to file字符串中的换行符未传递到文件
【发布时间】:2013-04-13 22:27:09
【问题描述】:

我看到了类似的 issie

Newlines in string not writing out to file

但这对我没有帮助,这是我的代码

 try { 
           String StringBudy =String.format(mailBuddy,System.getProperty("line.separator")); 

            FileOutputStream fOut = openFileOutput("My_Sms.txt",
                                                    MODE_WORLD_READABLE);
            OutputStreamWriter osw = new OutputStreamWriter(fOut); 

            osw.write(StringBudy);
            osw.flush();
            osw.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
    }

任何想法为什么字符串中的换行符没有写入文件?

【问题讨论】:

  • 你遇到了什么错误?
  • 我没有错误,My_Sms.txt 文件是一大行,因为“mailBuddy”包含很多小行
  • 如果你改变 osw.write(StringBudy);使用 ows.write(StringBudy + System.getProperty("line.separator")); ?
  • 没有改变输出文件...还是一长行
  • @JesusDimrix 我遇到了类似的问题,但我使用的是'\n' 和 BufferedWriter。我发现,要显示实际的行分隔符,我必须使用 newLine()。 newLine() 方法只是这样写:lineSeparator = java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("line.separator"));Source

标签: java android string newline fileoutputstream


【解决方案1】:

String.format() 只会将第一个 %s 替换为换行符。

例如:

String.format("this%sis%sa%stest", System.getProperty("line.separator"))

将产生

this
isatest

一种解决方案是将所有出现的%s 替换为换行符:

String str = mailBuddy.replace("%s", System.getProperty("line.separator"));

【讨论】:

  • 我写了 String StringBudy = mailBuddy.replace("%s", System.getProperty("line.separator"));并且文件的输出是一样的。还是一长串。
  • @JesusDimrix mailBuddy 的值是多少?
  • 很多短信。我将“mailBuddy”作为邮件发送,我创建的文件作为同一邮件的附件发送。我完美显示的邮件的好友,我创建的文件不是。
  • 如果你能给我创建文本文件并在其中放置带有行的字符串的工作代码。
  • @JesusDimrix -_- 您需要一些方法来确定应该将换行符插入到字符串的什么位置。例如,通过对字符串执行查找和替换。
【解决方案2】:

在创建使用 \n 换行的字符串时,请按照 windows 的要求使用 \r\n 。

【讨论】:

    猜你喜欢
    • 2010-11-11
    • 1970-01-01
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多