在 Java 中,GBK 到 UTF-8 的转换可以通过多种方式实现。下面我将介绍三种常见的实现方式,并提供每种方式的详细步骤流程和示例代码。
步骤流程:
示例代码:
import java.io.*;
public class GBKToUTF8Converter {
public static void convert(String gbkFilePath, String utf8FilePath) throws IOException {
try (BufferedReader gbkReader = new BufferedReader(new InputStreamReader(new FileInputStream(gbkFilePath), "GBK"));
BufferedWriter utf8Writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(utf8FilePath), "UTF-8"))) {
String line;
while ((line = gbkReader.readLine()) != null) {
utf8Writer.write(line);
utf8Writer.newLine();
}
}
}
public static void main(String[] args) {
String gbkFilePath = "path/to/sourcefile.txt";
String utf8FilePath = "path/to/convertedfile.txt";
try {
convert(gbkFilePath, utf8FilePath);
System.out.println("Conversion completed.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
步骤流程:
FileUtils
类提供的方法将 GBK 编码文件内容转换为 UTF-8 编码。Maven 依赖:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
Gradle 依赖:
implementation 'commons-io:commons-io:2.11.0'
示例代码:
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class GBKToUTF8Converter {
public static void convert(String gbkFilePath, String utf8FilePath) throws IOException {
File gbkFile = new File(gbkFilePath);
File utf8File = new File(utf8FilePath);
String content = FileUtils.readFileToString(gbkFile, "GBK");
FileUtils.writeStringToFile(utf8File, content, StandardCharsets.UTF_8);
}
public static void main(String[] args) {
String gbkFilePath = "path/to/sourcefile.txt";
String utf8FilePath = "path/to/convertedfile.txt";
try {
convert(gbkFilePath, utf8FilePath);
System.out.println("Conversion completed.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
步骤流程:
CSVReader
和 CSVWriter
类读取和写入 CSV 文件内容,OpenCSV 会处理字符编码的转换。Maven 依赖:
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.5.2</version>
</dependency>
Gradle 依赖:
implementation 'com.opencsv:opencsv:5.5.2'
示例代码:
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class GBKToUTF8Converter {
public static void convert(String gbkFilePath, String utf8FilePath) throws IOException {
try (CSVReader gbkReader = new CSVReader(new FileReader(gbkFilePath));
CSVWriter utf8Writer = new CSVWriter(new FileWriter(utf8FilePath))) {
String[] line;
while ((line = gbkReader.readNext()) != null) {
utf8Writer.writeNext(line);
}
}
}
public static void main(String[] args) {
String gbkFilePath = "path/to/sourcefile.csv";
String utf8FilePath = "path/to/convertedfile.csv";
try {
convert(gbkFilePath, utf8FilePath);
System.out.println("Conversion completed.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
这三种方法中,你可以根据具体需求选择适合你的方式来进行 GBK 到 UTF-8 的转换。