java 文件复制乱码
时间: 2023-10-16 17:07:58 浏览: 47
你好!在Java中进行文件复制时出现乱码的问题通常是由于字符编码不正确导致的。要解决这个问题,你可以使用字节流来进行文件复制,而不是字符流。以下是一个简单的示例代码:
```java
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
String sourceFile = "source.txt";
String destinationFile = "destination.txt";
try (InputStream in = new FileInputStream(sourceFile);
OutputStream out = new FileOutputStream(destinationFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
System.out.println("文件复制成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
请确保源文件和目标文件路径正确,并适当处理可能抛出的异常。这段代码将使用字节流从源文件读取数据,并使用字节流将数据写入目标文件,这样就可以避免乱码问题。
希望这可以帮助到你!如果有其他问题,请随时提问。