用java将UTF编码的文本文件src,复制到GBK编码的文本文件dest中,并输出dest文件的内容
时间: 2024-01-21 17:18:02 浏览: 29
可以使用Java的InputStreamReader和OutputStreamWriter来实现UTF-8到GBK的转换,同时使用BufferedReader和BufferedWriter来读写文件。
以下是示例代码:
```java
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
// 指定输入文件和输出文件
File srcFile = new File("src.txt");
File destFile = new File("dest.txt");
// 创建输入流和输出流
FileInputStream fis = new FileInputStream(srcFile);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr);
FileOutputStream fos = new FileOutputStream(destFile);
OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
BufferedWriter bw = new BufferedWriter(osw);
// 读取输入文件并写入输出文件
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
// 关闭流
br.close();
bw.close();
// 输出目标文件的内容
FileInputStream fis2 = new FileInputStream(destFile);
InputStreamReader isr2 = new InputStreamReader(fis2, "GBK");
BufferedReader br2 = new BufferedReader(isr2);
while ((line = br2.readLine()) != null) {
System.out.println(line);
}
// 关闭流
br2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在运行程序之前,需要先创建一个名为src.txt的UTF-8编码文件,文件中可以包含任意字符串。运行程序后,会将src.txt文件中的内容复制到名为dest.txt的GBK编码文件中,并输出dest.txt文件的内容。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)
![](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)