java复制文件及转码
时间: 2024-05-13 17:16:21 浏览: 22
Java复制文件可以使用`java.io`包的`FileInputStream`和`FileOutputStream`类,转码则需要使用`java.nio.charset`包的`Charset`类和`java.nio.charset`包的`CharsetEncoder`和`CharsetDecoder`类。
以下是一个示例代码,将一个UTF-8编码的文件复制为GBK编码的文件:
```java
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CharsetDecoder;
public class FileCopyWithEncoding {
public static void main(String[] args) {
try {
// 读取UTF-8编码的文件
FileInputStream fis = new FileInputStream("source.txt");
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr);
// 写入GBK编码的文件
FileOutputStream fos = new FileOutputStream("target.txt");
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();
isr.close();
fis.close();
bw.close();
osw.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上述代码中,`InputStreamReader`和`OutputStreamWriter`类用于将字节流转换为字符流,并指定编码格式。`BufferedReader`和`BufferedWriter`则用于逐行读取和写入文件,提高效率。最后,记得关闭文件流,以释放系统资源。
相关推荐
![](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)