Java当中的IO(二)

转载请注明出处:http://blog.youkuaiyun.com/u011569040/article/details/45113569


主要内容:

1.大文件的读写方法

2.字符流的使用方法


如果要读取一个1G的大文件,不可能申请一个1024*1024*1024字节的数组,只能通过循环一点一点的读取。


创建from.txt 和 to.txt ,from.txt里面有一篇英文文章

import java.io.FileInputStream;
import java.io.FileOutputStream;

//第一步:导入类

class Text{
	public static void main(String args []){
		//申明输入流引用
		FileInputStream fis = null;
		//申明输出流的引用
		FileOutputStream fos = null;
		try{
			//生成代表输入流的对象
			fis = new FileInputStream("d:/code/from.txt");
			//生成代表输出流的对象
			fos = new FileOutputStream("d:/code/to.txt");
			//生成一个字节数组
			byte [] buffer = new byte[1024];
			while(true){
				//调用输入流对象的read()方法,读取数据
				int temp = fis.read(buffer,0,buffer.length);
				if(temp == -1){
					//当数据读完后,再来一次循环时,返回值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);
			}
		}	
		
	}
}


//字符流:读写文件时,以字符为基础
//Reader<--FileReader int read(char [] c,int off,int len)
//Writer<--FileWriter void write(char [] c,int off,int len)
//他们类似字符流里面的 InputSream 、OutputStream、FileInputStream和FileOutputStream

import java.io.*;

public class TestChar{
	public static void main(String args []){
		FileReader fr = null;
		FileWriter fw = null;
		try{
			fr = new FileReader("d:/code/from.txt");
			fw = new FileWriter("d:/code/to.txt");
			
			char [] buffer = new char[100];
			int temp = fr.read(buffer,0,buffer.length);
			fw.write(buffer,0,temp);
		}
		catch(Exception e){
			System.out.println(e);
		}
		finally{
			try{
				fr.close();
				fw.close();
			}
			catch(Exception e){
				System.out.println(e);
			}
		}
	}
}

处理大文件和前一篇一样,加入几行代码循环一下就好

//字符流:读写文件时,以字符为基础
//Reader<--FileReader int read(char [] c,int off,int len)
//Writer<--FileWriter void write(char [] c,int off,int len)
//他们类似字符流里面的 InputSream 、OutputStream、FileInputStream和FileOutputStream

import java.io.*;

public class TestChar{
	public static void main(String args []){
		FileReader fr = null;
		FileWriter fw = null;
		try{
			fr = new FileReader("d:/code/from.txt");
			fw = new FileWriter("d:/code/to.txt");
			
			char [] buffer = new char[1024];
			while(true){
				int temp = fr.read(buffer,0,buffer.length);
				
				if(temp == -1){
					break;
				}
				
				fw.write(buffer,0,temp);
			}
		}
		catch(Exception e){
			System.out.println(e);
		}
		finally{
			try{
				fr.close();
				fw.close();
			}
			catch(Exception e){
				System.out.println(e);
			}
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值