Java BufferedReader和BufferedWriter示例

沐子 阅读 876 发表时间 2019-02-25 17:57:05
java

BufferedReaderBufferedWriter分别使用内部缓冲区来存储数据,同时进行读写。BufferedReader提供了一个新方法readLine(),它读取一行并返回一个String(不带行分隔符)。

以下示例显示了BufferedReaderBufferedWriter的使用。

文件:BufferedReaderWriterExample.java 

package com.yiibai.tutorial.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author yiibai
 */
public class BufferedReaderWriterExample {
    public static void main(String[] args) {
        File file = new File("file.txt");

        /*Writing file using BufferedWriter*/
        FileWriter fileWriter = null;
        BufferedWriter bufferedWriter =null;
        try {
            fileWriter=new FileWriter(file);
            bufferedWriter =new BufferedWriter(fileWriter);
            bufferedWriter.write("This is an example \n");
            bufferedWriter.write("of using BufferedWriter and \n");
            bufferedWriter.write("BufferedReader.");
            bufferedWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(fileWriter!=null){
                    fileWriter.close();
                }
                if(bufferedWriter!=null){
                    bufferedWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        /*Reading file using BufferedReader*/
        FileReader fileReader=null;
        BufferedReader bufferedReader=null;
        try {
            fileReader =new FileReader(file);
            bufferedReader=new BufferedReader(fileReader);
            String line=null;
            while((line=bufferedReader.readLine())!=null){
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(fileReader!=null){
                    fileReader.close();
                }
                if(bufferedReader!=null){
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

执行上面示例代码,得到以下结果(需要有文件:file.txt):

This is an example 
of using BufferedWriter and 
BufferedReader.


0个回复
有思考的问答, 才是有价值的问答, 否则将无任何记录价值.
关注极客云图了解更多内容