题目:使用流技术将一张图片从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();
			}
		}
	}
}

运行结果

异常

  1. 在输入流和输出流中,路径错误会导致报空指针异常。
  2. java中路径用双斜杠是因为转义字符原因,其实还是一个。