Java IO流基础

来源:互联网 发布:杭州软件外包公司 编辑:程序博客网 时间:2024/05/15 16:42

1.字节流(byte stream):为处理字节的输入和输出提供了方便的方法。例如使用字节流读取或书写二进制数据。

2.字符流(character stream):为字符的输入和输出处理提供了方便。

字节流/字符流:Java中,以stream结尾的都为字节流,以reader、writer结尾的为字符流。

注:在最底层,所有的输入/输出都是字节形式的。

字节流/字符流读、写文件代码如下

private String filePath="F:/java测试.txt";    /**     *      * @Description:用字节流读取文件     * @throws IOException: 返回结果描述     * @return void: 返回值类型     * @throws     */    public void readFileByByte() throws IOException{        //读取文件        FileInputStream fis=new FileInputStream(filePath);        //估算文件的长度        int size = fis.available();        for (int i=0;i<size;i++) {            //读取每个字节的数据            char a=(char) fis.read();            System.out.println(a);        }        //关闭输入流        fis.close();    }    /**     *      * @Description:字符流读取文件     * @throws IOException: 返回结果描述     * @return void: 返回值类型     * @throws     */    public void readFileByCharacter() throws IOException{        //创建字符流文件读取对象        FileReader fr=new FileReader(filePath);        //为文件读取对象建立缓冲区        BufferedReader br=new BufferedReader(fr);        String str=null;        //br.readLine()从文件中读取一行数据,以回车为结束符,如果没有可读数据返回null        while((str=br.readLine())!=null){            System.out.println(str);        }        //关闭流        br.close();        fr.close();    }    /**     *      * @Description:用字节流写文件     * @throws IOException: 返回结果描述     * @return void: 返回值类型     * @throws     */    public void writeFileByByte() throws IOException{        //写文件        FileOutputStream fos=new FileOutputStream(filePath);        String str="站在java的角度来记忆,文件输出流为FileOutputStream,文件输入流为FileInputStream";        byte[] b=str.getBytes();        fos.write(b);//写入目标文件        fos.close();//关闭输出流    }    /**     *      * @Description:字符流写文件     * @throws IOException: 返回结果描述     * @return void: 返回值类型     * @throws     */    public void writeFileByCharacter() throws IOException{        FileWriter fw=new FileWriter(filePath);//创建文件写入对象        String str="站在java的角度来记忆,文件输出流为FileOutputStream,文件输入流为FileInputStream";        fw.write(str);        fw.close();    }
0 0
原创粉丝点击