应用程序(Java 1.6)在Linux平台上运行,我创建了一个ISO-8859-1编码的文件 像这样
File localTempDir = new File(tempDir);
String encoding = TextUtils.ISO_8859_1;
try {
String fileName = String.format(fileNameFormat, sdf.format(new Date()));
tmpFile = File.createTempFile(fileName, "", localTempDir);
log.info("Created file " + tmpFile.getAbsolutePath());
OutputStreamWriter outputStreamWriter;
if(StringUtils.isNotBlank(encoding)){
outputStreamWriter = new OutputStreamWriter(new FileOutputStream(tmpFile), Charset.forName(encoding));
}else{
outputStreamWriter = new OutputStreamWriter(new FileOutputStream(tmpFile));
}
BufferedWriter out = new BufferedWriter(outputStreamWriter);
out.write(content);
log.debug("With content " + content);
out.flush();
out.close();
} catch (Exception e) {
log.error("Failed to create file", e);
}
return tmpFile;
}`
但仍然可以获得UTF8编码的文件。任何想法为什么?
答案 0 :(得分:0)
首先简化。试试这个:
File localTempDir = new File(tempDir);
String encoding = "ISO-8859-1"; // "Cp1252" = Windows Latin 1
try {
String fileName = String.format(fileNameFormat, sdf.format(new Date()));
tmpFile = File.createTempFile(fileName, "", localTempDir);
log.info("Created file " + tmpFile.getAbsolutePath());
OutputStreamWriter outputStreamWriter;
if (!encoding.isEmpty()) {
outputStreamWriter = new OutputStreamWriter(new FileOutputStream(tmpFile), encoding);
} else {
outputStreamWriter = new OutputStreamWriter(new FileOutputStream(tmpFile));
}
PrintWriter out = new PrintWriter(new BufferedWriter(outputStreamWriter));
try {
out.print(content);
log.debug("With content " + content);
finally {
out.close();
}
} catch (Exception e) {
log.error("Failed to create file", e);
}
return tmpFile;
}