以下代码尝试将换行符引入字节数组并将字节数组写入文件。
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();
}
}
}
新文件的内容为:newyorkdc
我的期望是:
纽约
直流
我试图将'\n'
强制转换为(byte)'\n'
,但无济于事。
解决方案:将阵列初始化更改为
byte[] cities = { 'n', 'e', 'w', 'y', 'o', 'r', 'k', '\r','\n', 'd', 'c' };
我曾使用Notepad ++来查看文件的内容。我想它会抑制换行符,但接受回车后跟换行组合。
答案 0 :(得分:3)
新行字符取决于操作系统,你应该检索它调用System.getProperty(“line.separator”)
或者更好的是,如果您正在编写文本文件,则应使用BufferedWriter,其中包含newLine()方法来编写独立于操作系统的行分隔符
答案 1 :(得分:1)
您可以通过阅读和打印文件证明其有效。
import java.io.*;
public class Main {
public static void main(String args[]) {
String filename = "newfile.txt";
byte[] cities = {'n', 'e', 'w', 'y', 'o', 'r', 'k', '\n', 'd', 'c'};
FileOutputStream outfile = null;
try {
outfile = new FileOutputStream(filename);
outfile.write(cities);
outfile.close();
BufferedReader in = new BufferedReader(new FileReader(filename));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
byte[] cities2 = {'n', 'e', 'w', 'y', 'o', 'r', 'k', 'd', 'c'};
outfile = null;
try {
outfile = new FileOutputStream(filename);
outfile.write(cities2);
outfile.close();
BufferedReader in = new BufferedReader(new FileReader(filename));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
测试
newyork
dc
newyorkdc