java字符流、字节流问题

注意:

1、字节流和字符流使用完后一定要关流。后开先关的原则

fis.close/fos.close

2、缓冲输出流的刷新

bw.flush().

   

字节流:以字节的形式读取文件,可以读取文本和多媒体。

FileInputStream/FileOutputStream---ByteArrayInputStream

        //字节流

        private static void inputStream() throws Exception{

            FileInputStream fis=new FileInputStream("a.txt");

            FileOutputStream fos=new FileOutputStream("f.txt");

   

            //fis.available() :文本字节大小

byte[] temp = new byte[fis.available()];

            fis.read(temp);//将源文件读取到temp

            fos.write(temp);//temp中的文件写到f.txt

            String str=new String(temp,"utf-8");

            System.out.println("str="+str);打印文本内容

            Byte[] temp = new byte[1024];

            Int len ;

            While((len = fis.read(temp)) != -1){

                Fos.writer(temp,0,len);

            }

        }

   

字符流:以字符的形式读取文件,只用于读取文本,读取多媒体会乱码。

FileReader / FileWriter

缓冲流:又称包装流,处理文件的输入输出事最快的,一般使用较多

BufferedReader/BufferedWriter

    //字符流+包装流

    privatestaticvoidReadIO()throwsException{

        FileReader fr=new FileReader(new  File("a.txt"));

        FileWriter fw=new FileWriter(new  File("c.txt"));

        BufferedReader br=new BufferedReader(fr);

        BufferedWriter bw=new BufferedWriter(fw);

        Stringstr="";

        StringstrAll="";

        while((str=br.readLine())!=null){

        strAll+=str;

        System.out.println("---"+str);

        bw.write(str);

        bw.newLine();

        bw.flush();

        }

        System.out.println("+++"+strAll);

    }

   

转换流:表现形式,以字节流读取以字符流输出

ReaderInputStream / WriterOutputStream

    //转换流的使用

    privatestaticvoidtestInputStreamReader()throwsException{

        BufferedReaderbr=newBufferedReader(newInputStreamReader(newFileInputStream("a.txt")));

        BufferedWriterbw=newBufferedWriter(newOutputStreamWriter(newFileOutputStream("g.txt")));

        Stringstr;

        while((str=br.readLine())!=null){

         bw.write(str);

         bw.newLine();

         bw.flush();

     }

    }

   

参考博客:https://www.cnblogs.com/joyco773/p/7966320.html

posted @ 2020-10-30 00:08  黑质白章  阅读(149)  评论(0编辑  收藏  举报