2 文件流,操作字节文件

文件流,操作字节文件

FileInputStream

FileOutputStream

package IO;

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

import javax.swing.plaf.synth.SynthScrollBarUI;
import org.junit.Test;

//文件流,操作字节文件
//FileInputStream
//FileOutputStream
public class fileInputStream {
	//不能使用字符流处理图片和数据
	//文本文件.txt .java .c .cpp 字符流
	//非文本文件 图片视频 .doc .ppt 字节流
	@Test
	//处理文本文件;字符不会出错,文字可能会;由于数组5 个子节,一个汉字3个子节
	//打印String会出错
	public void  testFileInputStream() throws IOException{
		// 1 文件
		File file = new File("hello.txt");
		//2 流
		FileInputStream fis = new FileInputStream(file);
		//3 读数据
		byte[] by = new byte[5];
		int len;
		while((len=fis.read(by))!=-1){
			String string = new String(by,0,len);
			System.out.print(string);
		}
		// 4 关闭资源
		fis.close();
	}
	
	@Test
	public void testFileInputStream1(){
		FileInputStream fis = null;
		FileOutputStream fos = null;
		
		try {
			File file1 = new File("1.png");
			File file2 = new File("1_1.png");
			fis = new FileInputStream(file1);
			fos = new FileOutputStream(file2);
			byte[] by = new byte[5];
			int len;
			while ((len = fis.read(by)) != -1) {
				fos.write(by);
			} 
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			if(fis != null){
				try {
					fis.close();
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
			if(fos!=null){
				try {
					fos.close();
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
		}
	}
	
	//指定路径下文件的复制
	public void copyFile(String inputPath,String outputPath){
		FileInputStream fis = null;
		FileOutputStream fos = null;
		
		try {
			File file1 = new File(inputPath);
			File file2 = new File(outputPath);
			fis = new FileInputStream(file1);
			fos = new FileOutputStream(file2);
			byte[] by = new byte[1024];
			int len;
			while ((len = fis.read(by)) != -1) {
				fos.write(by);
			} 
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			if(fis != null){
				try {
					fis.close();
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
			if(fos!=null){
				try {
					fos.close();
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
		}
	}
	@Test
	//复制文件,文字不会出错,不在内存层面读出来
	public void testCopy(){
		long start = System.currentTimeMillis();
		copyFile("D:\\桌面文件\\1.mp4","D:\\桌面文件\\2.mp4" );	
		long end = System.currentTimeMillis();
		System.out.println("复制操作花费的时间:"+(end-start));
	}
	
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值