[英]How to write a UTF-8 file with Java?
I have some current code and the problem is its creating a 1252 codepage file, i want to force it to create a UTF-8 file我有一些当前代码,问题是它创建了一个 1252 代码页文件,我想强制它创建一个 UTF-8 文件
Can anyone help me with this code, as i say it currently works... but i need to force the save on utf.. can i pass a parameter or something??任何人都可以帮我处理这段代码,正如我所说,它目前可以工作......但我需要强制保存在 utf 上......我可以传递参数或其他东西吗?
this is what i have, any help really appreciated这就是我所拥有的,非常感谢任何帮助
var out = new java.io.FileWriter( new java.io.File( path )),
text = new java.lang.String( src || "" );
out.write( text, 0, text.length() );
out.flush();
out.close();
Instead of using FileWriter
, create a FileOutputStream
.创建一个
FileOutputStream
而不是使用FileWriter
。 You can then wrap this in an OutputStreamWriter
, which allows you to pass an encoding in the constructor.然后,您可以将其包装在一个
OutputStreamWriter
,这允许您在构造函数中传递编码。 Then you can write your data to that inside a try-with-resources Statement :然后,您可以将数据写入try-with-resources 语句中:
try (OutputStreamWriter writer =
new OutputStreamWriter(new FileOutputStream(PROPERTIES_FILE), StandardCharsets.UTF_8))
// do stuff
}
Try this试试这个
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("outfilename"), "UTF-8"));
try {
out.write(aString);
} finally {
out.close();
}
Try using FileUtils.write
from Apache Commons.尝试使用 Apache Commons 中的
FileUtils.write
。
You should be able to do something like:您应该能够执行以下操作:
File f = new File("output.txt");
FileUtils.writeStringToFile(f, document.outerHtml(), "UTF-8");
This will create the file if it does not exist.如果文件不存在,这将创建该文件。
Since Java 7 you can do the same with Files.newBufferedWriter
a little more succinctly:从 Java 7 开始,你可以更简洁地对
Files.newBufferedWriter
做同样的Files.newBufferedWriter
:
Path logFile = Paths.get("/tmp/example.txt");
try (BufferedWriter writer = Files.newBufferedWriter(logFile, StandardCharsets.UTF_8)) {
writer.write("Hello World!");
// ...
}
All of the answers given here wont work since java's UTF-8 writing is bugged.由于 java 的 UTF-8 编写被窃听,这里给出的所有答案都不起作用。
http://tripoverit.blogspot.com/2007/04/javas-utf-8-and-unicode-writing-is.html http://tripoverit.blogspot.com/2007/04/javas-utf-8-and-unicode-writing-is.html
var out = new java.io.PrintWriter(new java.io.File(path), "UTF-8");
text = new java.lang.String( src || "" );
out.print(text);
out.flush();
out.close();
The Java 7 Files utility type is useful for working with files: Java 7 Files 实用程序类型对于处理文件很有用:
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.*;
public class WriteReadUtf8 {
public static void main(String[] args) throws IOException {
List<String> lines = Arrays.asList("These", "are", "lines");
Path textFile = Paths.get("foo.txt");
Files.write(textFile, lines, StandardCharsets.UTF_8);
List<String> read = Files.readAllLines(textFile, StandardCharsets.UTF_8);
System.out.println(lines.equals(read));
}
}
The Java 8 version allows you to omit the Charset argument - the methods default to UTF-8. Java 8 版本允许您省略Charset参数 - 方法默认为 UTF-8。
Below sample code can read file line by line and write new file in UTF-8 format.下面的示例代码可以逐行读取文件并以 UTF-8 格式写入新文件。 Also, i am explicitly specifying Cp1252 encoding.
另外,我明确指定了 Cp1252 编码。
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream("c:\\filenonUTF.txt"),
"Cp1252"));
String line;
Writer out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(
"c:\\fileUTF.txt"), "UTF-8"));
try {
while ((line = br.readLine()) != null) {
out.write(line);
out.write("\n");
}
} finally {
br.close();
out.close();
}
}
Here is an example of writing UTF-8 characters in the Eclipse IDE and to a File.下面是将 UTF-8 个字符写入 Eclipse IDE 和一个文件的例子。
For Eclipse.simply set the Encoding to UTF-8 from Run -> Run Configurations -> Common
Common Dialog对于 Eclipse。只需从
Run -> Run Configurations -> Common
通用对话框中将编码设置为 UTF-8
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
public class UTF_8_Example {
/**
* Example of printing UTF-8 characters inside Eclipse IDE and a File.
* <p>
* For eclipse, you must go to Run -> Run Configurations -> Common
* and set Encoding to UTF-8.
* <p>
* @param args
*/
public static void main(String[] args) {
BufferedWriter writer = null;
try {
///////////////////////////////////////////////////////////////////
// WRITE UTF-8 WITHIN ECLIPSE EDITOR
///////////////////////////////////////////////////////////////////
char character = '►';
int code = character;
char hex = '\u25ba';
String value = "[" + Integer.toHexString(code) + "][\u25ba][" + character + "][" + (char)code + "][" + hex + "]";
System.out.println(value);
///////////////////////////////////////////////////////////////////
// WRITE UTF-8 TO A FILE
///////////////////////////////////////////////////////////////////
File file = new File("UTF_8_EXAMPLE.TXT");
FileOutputStream fileOutputStream = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
writer = new BufferedWriter(outputStreamWriter);
writer.write(value);
}
catch(Throwable e) {
throw new RuntimeException(e);
}
finally {
try {
if(writer != null) { writer.close(); }
}
catch(Throwable e) {
throw new RuntimeException(e);
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.