JAVA文件流操作

//使用此方法不能读取大型文件
public class ReadFile {
	public static void main(String[] args) {
		byte bytes[] =new byte[1024];//定义缓冲区大小
		int n=0;//得到实际读取的字节数
		File file = new File("C:/Users/Chenxr/Desktop/卡密.txt");//定义读取的文件
		try {
			FileInputStream fis = new FileInputStream(file);
			try {
				while ((n=fis.read(bytes))!=-1) {
					//下一个数据字节,如果到达流末尾,则返回 -1。
					String string= new String(bytes, 0, n);
					System.out.println(string);
				}
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}finally{
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}

运用此方法可以读取大型文件,原理:逐行读取缓冲区

public class ReadLargeFile {

	// 此方法可以读取大文件
	public static void main(String[] args) {
		byte[] buf = new byte[1];// 存储数据的内部缓冲区数组
		int n = 0;//
		String string;
		File file = new File("C:/Users/Chenxr/Desktop/卡密.txt");
		try {
			FileReader f1 = new FileReader(file);//读取文件流
			BufferedReader br  =new BufferedReader(f1);//读取到输入流
			while ((string=br.readLine())!=null) {
				System.out.println(string);
				
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

}
//拷贝大型文件常用方法 bufferedInputStream
public class copyFile {
	public static void main(String[] args) {

		
		byte buf[] = new byte[10];// 定义缓冲区
		int rd;
		try {

			FileInputStream f1 = new FileInputStream("D:/text.doc");//
			FileOutputStream f2 = new FileOutputStream("D:/copy.doc");
			BufferedInputStream bfi= new BufferedInputStream(f1);
			BufferedOutputStream bfo = new BufferedOutputStream(f2);

			while ((rd = bfi.read(buf, 0, 1)) != -1) /*将各字节读取到指定的 byte 数组中,若到结尾则返回-1*/
			{
				bfo.write(buf,0,1);//将内容写到f2文件中
			}
			bfi.close();
			bfo.close();
			f1.close();
			f2.close();// 输入操作完成(复制操作)

		} catch (IOException e) {
			// TODO: handle excesption
		}

	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值