Windows中的行分隔符

时间:2014-05-27 19:19:54

标签: java string file newline

我想将一些单词保存到* .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记事本中打开)。

3 个答案:

答案 0 :(得分: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”)?

答案 1 :(得分:2)

base64 URI方案中使用data

<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

答案 2 :(得分:1)

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

由于我认为您在WebContainer中工作,因为您使用JSP结构,您还可以实现一个返回所请求数据的Servlet。