IO流用字符流赋值图片
时间: 2023-10-28 20:46:24 浏览: 48
抱歉,IO流中的字符流主要用于处理文本数据,而图片属于二进制数据。如果要将图片赋值给字符流,可能会导致数据损坏。正确的做法是使用字节流来处理图片数据。可以使用字节流读取图片文件,并将其写入到指定的输出流中,例如:
```java
import java.io.*;
public class ImageCopy {
public static void main(String[] args) {
String sourceFile = "path/to/source/image.jpg";
String destinationFile = "path/to/destination/image.jpg";
try (FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(destinationFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
System.out.println("Image copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上述示例中,我们使用字节流来读取源图片文件(`FileInputStream`),并使用字节流将数据写入到目标图片文件(`FileOutputStream`)。这样可以确保二进制数据的完整性。