在Java中处理UTF字符串有多种方法
// -*- coding: utf-8 -*-
或者
// coding=utf-8
String utf8String = new String("你好,世界!", "UTF-8");
读取UTF-8字符串:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadUtf8 {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("input.txt", "UTF-8"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
写入UTF-8字符串:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteUtf8 {
public static void main(String[] args) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
bw.write("你好,世界!");
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class Utf8FileExample {
public static void main(String[] args) {
Path path = Paths.get("example.txt");
// 读取UTF-8文件
List<String> lines;
try {
lines = Files.readAllLines(path, StandardCharsets.UTF_8);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// 写入UTF-8文件
String content = "你好,世界!";
try {
Files.write(path, content.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
}
}
}
这些方法可以帮助您在Java中处理UTF-8字符串。注意在处理文件时始终指定编码,以避免出现编码相关的问题。