java实现gbk转utf8
时间: 2023-07-26 11:03:56 浏览: 57
在Java中,可以使用`java.nio.charset.Charset`类来实现GBK到UTF-8的转换。下面是一个简单的示例:
```java
import java.nio.charset.Charset;
import java.io.*;
public class GBK2UTF8 {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("input.txt");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("GBK"));
BufferedReader br = new BufferedReader(isr);
FileOutputStream fos = new FileOutputStream("output.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, Charset.forName("UTF-8"));
BufferedWriter bw = new BufferedWriter(osw);
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
br.close();
isr.close();
fis.close();
bw.close();
osw.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们使用`java.nio.charset.Charset`类中的`forName`方法来获取指定编码格式的`Charset`对象,然后使用转换流(`InputStreamReader`和`OutputStreamWriter`)来读取和写入文件。注意:当使用转换流时,需要指定输入文件的编码格式为GBK,输出文件的编码格式为UTF-8。
相关推荐
![jar](https://img-home.csdnimg.cn/images/20210720083455.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![jar](https://img-home.csdnimg.cn/images/20210720083455.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)