Java BufferedReader和BufferedWriter示例

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.

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/276197.html

(0)
上一篇 2023年2月28日 05:33
下一篇 2023年2月28日 05:33

相关推荐

发表回复

登录后才能评论