JAVA IO 字符流 FileReader FileWriter

摘抄自 b站尚硅谷JAVA视频教程

FileReader fileReader = new FileReader(file)

read()方法的使用:

 File file = new File("hello.txt");
        FileReader fileReader = null;
        try{

             fileReader= new FileReader(file);
            int data;
            while((data=fileReader.read())!=-1){
                System.out.print((char)data);
            }
        } catch (IOException e){
            e.printStackTrace();
        }finally {
            if(fileReader!=null){
                try{
                    fileReader.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }

read(char *)的使用方法

File file = new File("hello.txt");
        FileReader fileReader = null;
        try{

            fileReader= new FileReader(file);
            char [] data = new char[5];
            int len=-1;
            while((len=fileReader.read(data))!=-1){
                System.out.print(new String(data,0,len));
            }
        } catch (IOException e){
            e.printStackTrace();
        }finally {
            if(fileReader!=null){
                try{
                    fileReader.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }

write(file,append=true/false)方法

若没有file不存在,则创建

若file存在

  append=true:追加内容

  append=false:覆盖内容(默认)

File file = null;
        file = new File("hi.txt");
        FileWriter fw=null;
        try {
            fw = new FileWriter(file);
            fw.write("hello world");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fw!=null){
                try{
                    fw.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }

猜你喜欢

转载自www.cnblogs.com/superxuezhazha/p/12340692.html