字符串中的换行符不写入文件 [英] Newlines in string not writing out to file
问题描述
String output =Hello \\\
there!;
BufferedWriter oFile = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(test.txt),UTF-16));
System.out.println(output);
oFile.write(输出);
oFile.close();
打印语句输出
你好!
有!
但文件内容是
Hellothere!
为什么我的新行没有写入文件
您应该尝试使用
System.getProperty(line.separator)
这是一个未经测试的例子 p>
String output = String.format(Hello%sthere!,System.getProperty(line.separator));
BufferedWriter oFile = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(test.txt),UTF-16));
System.out.println(output);
oFile.write(输出);
oFile.close();
我还没有能够测试第一个
方法,因为
字符串中的换行符不会被写为
文件的新行
您确定那?你可以发布一些代码来显示具体的事实吗?
I'm trying to write a program that manipulates unicode strings read in from a file. I thought of two approaches - one where I read the whole file containing newlines in, perform a couple regex substitutions, and write it back out to another file; the other where I read in the file line by line and match individual lines and substitute on them and write them out. I haven't been able to test the first approach because the newlines in the string are not written as newlines to the file. Here is some example code to illustrate:
String output = "Hello\nthere!";
BufferedWriter oFile = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("test.txt"), "UTF-16"));
System.out.println(output);
oFile.write(output);
oFile.close();
The print statement outputs
Hello
there!
but the file contents are
Hellothere!
Why aren't my newlines being written to file?
You should try using
System.getProperty("line.separator")
Here is an untested example
String output = String.format("Hello%sthere!",System.getProperty("line.separator"));
BufferedWriter oFile = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("test.txt"), "UTF-16"));
System.out.println(output);
oFile.write(output);
oFile.close();
I haven't been able to test the first approach because the newlines in the string are not written as newlines to the file
Are you sure about that? Could you post some code that shows that specific fact?
这篇关于字符串中的换行符不写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!