使用FileReader以及FileWrite操作文本文件的示例

本文详细介绍了Java BufferedReader的使用方法,包括读取整个文件、按行读取文件和写文件的操作,并通过实例展示了如何实现这些功能。此外,还提供了一种改进的按行读取方式,以保留文件中的换行符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      java BufferedReader使用方法:

      public class BufferdReader extends Reader
      从字符输入流中读取文本,缓冲各个字符,从而提供字符、数组和行的高效读取。
       Reader 所作的每个读取请求都会导致对基础字符或字节流进行相应的读取请求。因此,建议用 BufferedReader 包装所有其 read() 操作可能开销很高的 Reader(如 FileReader 和 InputStreamReader)。例如,BufferedReader in = new BufferedReader(new FileReader("foo.in"));将缓冲指定文件的输入。如果没有缓冲,则每次调用 read() 或 readLine() 都会导致从文件中读取字节,并将其转换为字符后返回,而这是极其低效的。

1. 读取整个文件 

    private String readInfoFromFile(String fullPathFile) {

            File file = new File(fullPathFile);
            try {
                if (file.exists()) {
                    Log.d(TAG, "file exists, read it now.");
                    FileReader fr = new FileReader(file);
                    BufferedReader br = new BufferedReader(fr);


                    try {
                        int fileLength = (int)file.length();
                        char[] buf = new char[fileLength];

                        int readLen = br.read(buf, 0, fileLength);

                        br.close();

                        return new String(buf);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                } else {
                    Log.d(TAG, "file: " + fullPathFile + " does not exist.");
                    return null;
                }
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            }
            return null;
        }            

2. 按行读取文件

       File file = new File(fullPathFile);
       try {
           if (file.exists()) {
            Log.d(TAG, "file exists, read it now.");
            FileReader fr = new FileReader(file);

            BufferedReader br = new BufferedReader(fr);

    try {                  

     int n = 0;                   

     for (; ;) {

                        n++;
                        String temp = br.readLine();
                        Log.d(TAG, "read line" + n + ":");
                        Log.d(TAG, "" + temp);
                        if (temp == null) {
                            Log.d(TAG, "read over.");
                            br.close();
                            break;
                        } else {
                            content += temp;
                        }
                    }
              } catch (Exception ex) {
                    ex.printStackTrace();
    }
   }else {
           Log.d(TAG, "file: " + fullPathFile + " does not exist.");
           return null;
            }

            return content;       

  } catch (FileNotFoundException ex) {

            ex.printStackTrace();
        }

        return null;

但上面有个缺点,就是如果原文件中有回车换行,则丢了,所以,遇到这种情况,要么采用1的方式实现,要么如下写:

private String readFile(File file) {
    if (file == null || !file.exists() || !file.isFile())       return null;
    String result = new String();
    try {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line;
        while ((line = reader.readLine()) != null) {
            result += line + "\n";
        }
        reader.close();
        return result;
    } catch (FileNotFoundException e) {
        return null;
    } catch (Exception e) {
        Log.e(TAG, "readFile: Exception.", e);
        return null;
    }
}
即每读一行,主动加个"\n"即可。

3. 写文件


        private boolean saveToFile(String fullPathFile, String content) {
            File f = new File(fullPathFile);
            FileWriter fw;
            try {
                fw = new FileWriter(f);
                BufferedWriter bw = new BufferedWriter(fw);
                Log.d(TAG, "saveToFile(), writing now.");
                bw.write(content);
                bw.flush();
                bw.close();
                Log.d(TAG, "saveToFile(), writing complete.");
            } catch (IOException ex) {
                ex.printStackTrace();
                return false;
            }
            return true;
        }

或者比较简单的:

private boolean writeFile(File file, String contents) {
    if (file == null)   return false;
    try {
        FileWriter writer = new FileWriter(file);
        writer.write(contents);
        writer.close();
        return true;
    } catch (Exception e) {
        Log.e(TAG, "writeFile: Exception.", e);
        return false;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值