题目:使用流技术将一张图片从F:\images目录下,复制到D:\images目录下。
复制图片需要使用字节流,使用字符流复制会将图片字节码格式进行编码,可能会导致图片数据丢失。
public class CopyImg {
public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("E://img//1.jpg");
fos = new FileOutputStream("D://img//1.jpg");
byte[] b = new byte[1024];
int a = fis.read(b);
while (a != -1) {
fos.write(b);
a = fis.read(b);
}
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
运行结果
异常
- 在输入流和输出流中,路径错误会导致报空指针异常。
- java中路径用双斜杠是因为转义字符原因,其实还是一个。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)