Cha*_*pau 2 java arrays fileoutputstream
以下代码尝试将换行符引入字节数组并将字节数组写入文件。
import java.io.*;
public class WriteBytes {
public static void main(String args[]) {
byte[] cities = { 'n', 'e', 'w', 'y', 'o', 'r', 'k', '\n', 'd', 'c' };
FileOutputStream outfile = null;
try {
outfile = new FileOutputStream("newfile.txt");
outfile.write(cities);
outfile.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
新文件的内容是:newyorkdc
我所期望的是:
纽约
特区
我尝试打字'\n'但(byte)'\n'无济于事。
解决方案:将数组初始化改为
byte[] cities = { 'n', 'e', 'w', 'y', 'o', 'r', 'k', '\r','\n', 'd', 'c' };
Run Code Online (Sandbox Code Playgroud)
我使用 Notepad++ 查看文件的内容。我想它抑制了换行符,但接受了回车符和换行符组合。
新行字符取决于操作系统,您应该调用 System.getProperty("line.separator") 检索它
或者更好的是,如果您正在编写文本文件,您应该使用BufferedWriter,它具有 newLine() 方法来编写独立于操作系统的行分隔符
| 归档时间: |
|
| 查看次数: |
22128 次 |
| 最近记录: |