IO文件拷贝

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40301026/article/details/87869862

利用java的IO流实现文件的拷贝。思路:

以程序为中转站的作用,对接输入流和输出流。便实现了文件的拷贝。也就是对上一篇博客两种流的结合。

https://blog.csdn.net/qq_40301026/article/details/87869205

                                            

源文件存放在study02下,命名为:ta.jpg

   

package cn.liu.io2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyFile {
	public static void main(String[] args) {
		try {
			copyFile("ta.jpg","www.jpg");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public static void copyFile(String source,String aim) throws InterruptedException {
		//1.创建源(输入--->输出)
		File in = new File(source);
		File out = new File(aim);
		
		InputStream is = null;
		OutputStream os = null;
		try {
			//2.选择流(输入---->输出)
			is = new FileInputStream(in);
			os = new FileOutputStream(out);
			
			//3.操作(先从输入接受进来存程序,再从程序输出到指定位置)
			//3.1分段读取
			byte[] flush = new byte[1024*1];
			int len=-1;//记录缓冲池的长度
			while((len=is.read(flush))!=-1) {
				//3.2读进来后到后再给写出去
				os.write(flush,0,len);
			}
			os.flush();//每次再刷新一下缓冲池
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			//4.释放资源  分别关闭,先打后关
			try {
				while(os!=null) {
					os.close();
				}
				
				while(is!=null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

执行结果:

按F5进行刷新就可以看到:新建的文件(www.jpg)

                                                          

打开后看到成功:

                             

猜你喜欢

转载自blog.csdn.net/qq_40301026/article/details/87869862