Java中的IO流的运用拓展——对文件进行复制

通过java代码运用IO流对文件进行复制操作

在IO流中对文件进行各种操作很常见今天主要分享一下用字节流对图片文件的复制操作

文件的复制操作需要同时运用输入流和输出流,通俗易懂的理解就是一边读取一边写入。

文件通过字节输入流输入到运行内存中,从而通过字节输出流从内存中转入到磁盘中。这里强调运用字节流对图片文件进行复制就说明字符流用于复制图片或者视频是不可行的,所以在遇到对音视频或者图片的复制过程就选择字节流。

下面展示一些 内联代码片
public static void main(String[] args) {
    
    
		FileInputStream fileInput = null;
		FileOutputStream fileOutput = null;
		try {
    
    
			// 同时运用字节输出流和输入流
			fileInput = new FileInputStream("E:" + File.separator + "gou.jpg");
			fileOutput = new FileOutputStream("E:" + File.separator + "goucopy.jpg");
			byte[] array = new byte[1024 * 1];
			int len = 0;
			while ((len = fileInput.read(array)) != -1) {
    
    
				fileOutput.write(array, 0, len);
			}
		} catch (Exception e) {
    
    
			// TODO: handle exception
		} finally {
    
    
			if (fileInput != null) {
    
    
				try {
    
    
					// 在完成对文件的操作后记得关闭流
					fileInput.close();
				} catch (IOException e) {
    
    
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (fileOutput != null) {
    
    
				try {
    
    
					// 在完成对文件的操作后记得刷新和关闭流
					fileOutput.flush();
					fileOutput.close();
				} catch (IOException e) {
    
    
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

猜你喜欢

转载自blog.csdn.net/fdbshsshg/article/details/114002386