在写Java程序时,有时候我们需要将一个文件夹下的图片或者文件,复制到其他指定的文件夹中,这个时候就用到了IO流。
具体测试类代码如下:

public class Test08 {
 
	public static void main(String[] args) {
		long startTime = System.currentTimeMillis();
		File fromFile = new File("E:/file/3.docx");
		File toFile = new File("E:/file/file/3a.docx");
		InputStream is = null;
		OutputStream os = null;
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			is = new FileInputStream(fromFile);
			os = new FileOutputStream(toFile);
			// 创建缓冲流
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(os);
			int content = bis.read();
			while (content != -1) {
				// 使用缓冲流写数据
				bos.write(content);
				// 刷新
				bos.flush();
				content = bis.read();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
 
		long endTime = System.currentTimeMillis();
		System.out.println("复制功能完成,耗时:" + (endTime - startTime) + "毫秒");
 
	}
 
}

输出结果显示:
Java之图片或文件的复制_图片复制
以下测试了图片及两种文件,均成功:
Java之图片或文件的复制_图片复制_02