【问题标题】:Line separator for Windows in javajava中Windows的行分隔符
【发布时间】:2014-05-27 19:19:53
【问题描述】:

我想将一些单词保存到 *.txt 文件中。但是有一个条件:每个单词都必须换行。所以我写了这个:

String content ="";
String nl = System.lineSeparator();
content += "my" + nl + "some" + nl + "random" + nl + "words";

但这段代码不起作用 - 所有单词都在同一行。

所以我尝试使用特殊字符 - \r\n

String content ="";
content += "my" + "\r\n" + "some" + "\r\n" + "random" + "\r\n" + "words";

仍然没有用 - 在文件中所有单词都在同一行:

mysomerandomwords

除此之外:我的字符串content 被保存到文件中:

<a href="data:text/txt;charset=utf-8,<%=content%>" download="results.txt"><button class="button">Download</button></a>

我应该使用哪种分隔符将单词放在另一行中?

(我使用的是 Netbeans 8.0。文件在 Windows 记事本中打开)。

【问题讨论】:

  • 尝试对content进行URL编码。
  • 避免使用windows-notepad。如果您不想使用 Notepad++ 之类的东西,请尝试使用 windows 写字板,至少它会显示行分隔符。

标签: java string file newline


【解决方案1】:

data URI 方案中使用base64

<a href="data:text/txt;charset=utf-8;base64,<%=base64_content%>" download="results.txt"><button class="button">Download</button></a>

在你的 Java 代码中:

String content ="";
String nl = System.getProperty("line.separator");
content += "my" + nl + "some" + nl + "random" + nl + "words";
content = DatatypeConverter.printBase64Binary(content.getBytes("utf-8"));

演示:http://jsfiddle.net/bDRAq

【讨论】:

  • @1_bug 如果以正确的方式完成,则不会:jsfiddle.net/bDRAq(对不起,我错过了 base64,已更新)
【解决方案2】:

试试System.getProperty("line.separator")

在此处阅读有关 System Properties 的完整系统属性列表。

System类维护了一个描述当前工作环境配置的Properties对象。

"line.separator" - 操作系统用来在文本文件中分隔行

的序列

System.lineSeparator() 说明了什么?

返回系统相关的行分隔符字符串。它总是返回相同的值——系统属性 line.separator 的初始值。

在 UNIX 系统上,它返回“\n”;在 Microsoft Windows 系统上,它返回“\r\n”。


为什么要使用System.getProperty()

“line.separator”属性可以通过传递参数来改变,如下所示

java -Dline.separator=

看看Should I cache System.getProperty(“line.separator”)?

【讨论】:

  • 为什么?它与 System.lineSeparator() 有什么不同?
  • 这与System.lineSeparator() 有何不同,除了System.lineSeparator() 仅读取line.separator 系统属性一次?
  • @pingw33n 看看Oracle Java Tutorial on System Properties 对该属性的描述。
  • @Braj:没有任何改变。仍然所有单词都在同一行。
  • 为什么它不适合你?这是您的实际代码吗?请分享完整的代码以重现它。
【解决方案3】:

嗯,这取决于你如何写下内容。如果您将其写入文件系统上的文件,它很可能会正确结束。但是您并没有将它与您的程序一起保存到文件中,而是让浏览器通过在 html 文件中包含一个链接来做到这一点。在 HTML 中包含字符时,您需要使用 URLEncoder 类对其进行编码。

因为在我看来你是在一个 WebContainer 中工作,因为你是 JSP 结构,你也可以实现一个返回请求数据的 Servlet。

【讨论】:

  • 我试过 URLEncoder 并且它工作正常,但如果我有像“A=2”、“B=5”等字符串,它会返回“A+2”、“B+5”。跨度>
猜你喜欢
  • 2013-11-02
  • 1970-01-01
  • 2012-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-12
相关资源
最近更新 更多