IO一:字节流

字节流读取与写出时是以字节为基础的,换句话说就是以一个字节一个字节的读入和写出的

1.小文件的读取与写出

import java.io.*;
class TestIO{
	public static void main(String args []){
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try{
			fis = new FileInputStream("F:/javastudy/src/form.txt");
			byte [] buffer = new byte[100];
			//参数:byte类型的参数(读进来存放的位置),int类型的参数(在byte中开始存放的位置),
			//int类型的参数(要读取几个字节的参数)
			//返回值:int类型(本次总共读取了几个字节)
			int temp = fis.read(buffer,0,buffer.length);			
			fos = new FileOutputStream("F:/javastudy/src/to.txt");
			fos.write(buffer,0,temp);			
		}catch(Exception e){
			System.out.println(e);
		}finally{
			try{
				fis.close();
				fos.close();
			}catch(Exception e){
				System.out.println(e);
			}
		}
	}
}

2.大文件的读取与写出(与上面的程序相比多了一个循环,因为当文件太大时,不可能一下子将文件中的所有内容全部读进来,会占用大量的内存)

import java.io.*;
class TestIO{
	public static void main(String args []){
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try{
			fis = new FileInputStream("F:/javastudy/src/form.txt");
			fos = new FileOutputStream("F:/javastudy/src/to.txt");
			byte [] buffer = new byte[1024];
			while(true){
				int temp = fis.read(buffer,0,buffer.length);
				//当read()返回值为-1的时候,表示文件已经读取完毕
				if(temp == -1){
					break;
				}
				fos.write(buffer,0,temp);
			}			
		}catch(Exception e){
			System.out.println(e);
		}finally{
			try{
				fis.close();
				fos.close();
			}catch(Exception e){
				System.out.println(e);
			}
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值