java33java当中的IO(二)

大文件的读写方法

采用循环读取的方法,当read方法返回值为-1时,说明文件全部读取完毕跳出循环

while(true){
int temp = fils.read(buffer,0,1024);
if(temp == -1){
break;}
fos.write(buffer,0,temp);
}
  • 关闭IO流:
    关闭代码不可以放在while语句或者catch语句中,应该放在finally中,然后还有try catch结构包括在内。

字符流的使用方法

//字符流:读写文件时,以字符为基础

//字符输入流:Reader <--FileReader

//方法:  int read(char[]c,int off,int len)

//字符输出流:Writer <--FileWriter

//方法    void write(char[]c,int off,intlen)
import java.io.*;
public class TestChar{
    public static void main(String[] args){
        FileReader fr = null;
        FileWriter fw = null;
        try{
            fr = new FileReader("f:/src/from.txt");
            fw = new FileWriter("f:/src/to.txt");
            //char[] buffer = new char[100];
            //int temp = fr.read(buffer,0,buffer.length);

            /*for(int i = 0;i < buffer.length;i++){
                System.out.println(buffer[i]);
            }*/
            //fw.write(buffer,0,temp);
            int i = fr.read();
            while(i != -1) {
            fw.write(i);
        }
        catch(Exception e){
            System.out.println(e);
        }
        finally{
            try{
                fr.close();
                fw.close();
            }
            catch(Exception e){
                System.out.println(e);
            }
        }
    }
}

简便写法

import java.io.*;
public class TestBufferedReader {
    public static void main(String[] args) {

        try{
            BufferedReader br = new BufferedReader(new FileReader("f:/src/io.txt"));
            BufferedWriter bw = new BufferedWriter(new FileWriter("f:/src/read2.txt"));
            String m;
            do{
                m = br.readLine();
                if(m == null ){
                    break;
                }
                //System.out.println(m);
                bw.write(m,0,m.length());
                bw.newLine();
            } while(m != null);

            br.close();
            bw.close();
        }   
        catch(IOException e){
            e.printStackTrace();
        }


    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值