字符串中的换行符不写入文件 [英] Newlines in string not writing out to file

查看:178
本文介绍了字符串中的换行符不写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个程序来处理从文件读入的Unicode字符串。我想到了两种方法 - 一种是在其中读取包含换行符的整个文件,执行一些正则表达式替换,并将其写回到另一个文件;另一个我一行一行地在文件中读取并匹配个别行并替换它们并写出来。我还没有能够测试第一种方法,因为字符串中的换行符不被写为文件的换行符。下面是一些示例代码来说明:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆