问题:
程序主体大概是读入一个文件(utf-8编码),进行操作后然后写入另一个文件中;两个文件均为中文
在IDEA 上运行没有问题;但是到了终端,却出现了乱码;之后尝试了网上的设置;java -Dfile.encoding=utf-8,没有出现乱码了。但是各个中文字体之间出现了空格。怎么回事;下面是输出的主要程序:
private void writeFile(String toPath) {
File fileTo = new File(toPath);
if (!fileTo.exists()) {
for (String str : res) {
FileOutputStream fo = null;
PrintStream ps = null;
try {
fo = new FileOutputStream(fileTo, true);
ps = new PrintStream(fo);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
assert ps != null;
ps.print(str);
ps.close();
}
}
}
请参照如下代码尝试,先是按行读取文件的内容到list,然后在将list的内容以拼接的方式放到另一个文件中。
/**
* 读取文件内容
*
* @param filePathAndName 文件路径+文件名
* @param characterSet 字符编码
* @return 文件内容的字符串
*/
public static java.util.List<String> readFileContentToList(String filePathAndName, String characterSet) {
java.util.List<String> stringList = new ArrayList<>();
File file = new File(filePathAndName);
try {
if (!file.exists()) {
file.createNewFile();
}
InputStreamReader read = new InputStreamReader(new FileInputStream(file), characterSet);
BufferedReader reader = new BufferedReader(read);
String line = "";
while ((line = reader.readLine()) != null) {
stringList.add(line);
}
read.close();
} catch (Exception e) {
e.printStackTrace();
}
return stringList;
}
/**
* 将内容追加的方式写入到文件
*
* @param filePath 文件全路径
* @param conent 要追加的文本内容
*/
public static void appendFile(String filePath, String conent) {
File file = new File(filePath);
//文件不存在则创建一个
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, true)));
// "\r\n" 表示在结果回车换行
out.write(conent + "\r\n");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}