简体   繁体   English

如何在Java上断开字符串?

[英]How can I break the string on Java?

I need to write strings into ByteArrayOutputStream , but I need to write strings with breaking. 我需要将字符串写入ByteArrayOutputStream ,但是我需要将字符串写入中断。 I have tried to do it as example: 我试图做为例:

out.write("123".getBytes());
out.write("\n456".getBytes());

But '\\n' doesn't work. 但是'\\ n'不起作用。 Please, tell me, how can I fix it? 请告诉我,我该如何解决? Or suggest me alternative OutputStream for storing strings (this OS must allow to use breaking of lines) without making files. 或建议我使用其他OutputStream来存储字符串(此OS必须允许使用换行符)而不制作文件。 Thank you. 谢谢。

ByteArrayOutputStream stream = ...;
PrintStream printer = new PrintStream(stream, true); // auto-flush
printer.println("123"); // writes newline
printer.print("hello"); // no new line
printer.print(" world");
printer.println();

Note that this will generate platform-specific bytes. 请注意,这将生成特定于平台的字节。 Newlines can be \\n , \\r\\n or \\r . 换行符可以是\\n\\r\\n\\r The actual character sequence used is specified in system property line.separator . 使用的实际字符序列在系统属性line.separator指定。

Just use BufferedWriter it will manage line breaks for you ( bwinstance.newLine() ). 只需使用BufferedWriter ,它将为您管理换行符( bwinstance.newLine() )。 No matter on which OS you are running. 无论您在哪个操作系统上运行。

If you are looking for a system independent newline separator I would recommend using: 如果您正在寻找与系统无关的换行符,我建议使用:

System.getProperty("line.separator");

Rather than calling getProperty() every time, I would also store this value in a properly accessible variable. 而不是每次都调用getProperty() ,我还将这个值存储在适当访问的变量中。

This is also the ideal method if you are constructing strings prior to writing them, since this way you will not have to write each line separately. 如果要在编写字符串之前构造字符串,这也是一种理想的方法,因为这样您就不必分别编写每一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM