下面这段代码尝试在字节数组中引入换行符,并将字节数组写入文件。
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++来查看文件的内容,我认为它取消了换行符,但接受了回车和换行符组合。
发布于 2016-09-09 19:46:51
换行符依赖于操作系统,您应该调用System.getProperty("line.separator")来检索它
或者更好的做法是,如果您正在编写文本文件,则应该使用具有newLine()方法的BufferedWriter来编写独立于操作系统的行分隔符
发布于 2016-09-09 19:48:59
您可以通过读取和打印文件来证明它是有效的。
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
newyorkdchttps://stackoverflow.com/questions/39410670
复制相似问题