Java中的IO流(copyfile)举例

需求1:将D://工程天下.txt 拷贝到当前项目下 名字为new.txt
需求2:将D://美女.jpg 拷贝到当前项目下 名字为美女1.jpg
步骤
1:通过输入流读取D://工程天下.txt 到java程序中
2:通过输出流把工程天下.txt写到当前项目的文件中

public static void copyFile1(FileInputStream fis,
                          FileOutputStream fos) throws IOException{
		 int num = 0;
		 //读一个字节
		 int index = 0;
		 while((num = fis.read())!=-1){
			  //写一个字节
			 index++;
			 fos.write(num);
		 }
		 System.out.println(index);
		 fis.close();
		 fos.close();
		
		
	}
	/**
	 * 拷贝文件2  一次拷贝一个字节数组
	 * @param args
	 * @throws IOException 
	 */
	public static void copyFile2(FileInputStream fis,
	                         FileOutputStream fos) throws IOException{
		 int num = 0;
		 byte[] by = new byte[1024*1024];
		 //读一个字节数组
		 while((num = fis.read(by))!=-1){
			 //一次写一个字节数组  写入的是文件的实际长度
			 fos.write(by, 0, num);
		 }
		 fis.close();
		 fos.close();
		
		
	}
	/**
	 *   字节缓冲流拷贝文件  一次拷贝一个字节
	 * @param fis
	 * @param fos
	 * @throws IOException
	 */
	public static void copyFile3(BufferedOutputStream bos,
	                      BufferedInputStream bis) throws IOException{
		 int num = 0;
		 while((num = bis.read())!=-1){
			 bos.write(num);
		 }
		 //关闭流文件
		 bis.close();
		 bos.close();
	}
	
	/**
	 *   字节缓冲流拷贝文件  一次拷贝一个字节数组
	 * @param fis
	 * @param fos
	 * @throws IOException
	 */
	public static void copyFile4(BufferedOutputStream bos,
	                      BufferedInputStream bis) throws IOException{
		 int num = 0;
		 byte[] by = new byte[1024*1024];
		 while((num = bis.read(by))!=-1){
			 bos.write(by, 0, num);
		 }
		 //关闭流文件
		 bis.close();
		 bos.close();
	}
	
	
	
	public static void main(String[] args) throws IOException {
		FileInputStream fis = new FileInputStream("D://1.avi");
		FileOutputStream fos = new FileOutputStream("1.avi");
		
		//创建字节缓冲输出流以及输入流
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		BufferedInputStream bis = new BufferedInputStream(fis);
		
		long start = System.currentTimeMillis();
		//copyFile1(fis,fos);
		//copyFile2(fis,fos);
		//copyFile3(bos,bis);
		copyFile4(bos,bis);
		long end = System.currentTimeMillis();
		System.out.println(end-start);
		
	}

猜你喜欢

转载自blog.csdn.net/qq_44013790/article/details/85330348