在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();
}
}
}
寫入U(xiǎn)TF-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();
}
// 寫入U(xiǎn)TF-8文件
String content = "你好,世界!";
try {
Files.write(path, content.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
}
}
}
這些方法可以幫助您在Java中處理UTF-8字符串。注意在處理文件時(shí)始終指定編碼,以避免出現(xiàn)編碼相關(guān)的問題。