1 前言
为了降低耦合并提供强大的功能,Java提供了非常丰富多样的Stream类,如InputStream, OutputStream, BufferedStream等。强大的功能同样也是一把双刃剑,给使用记忆带来了很多麻烦,不是每个人都是天天使用Java的这些类,并把它们记得非常清楚。相信有很多和笔者一样的人,每次在使用的时候,都需要查看相应的代码。为了解决这个问题,笔者根据常用的功能,编写了一个简易的Java类,TextReader 专门用于文本的按行读取。
2 功能描述
这个类的主要就是按行读取文件。文件读取分为三步,打开,读取,关闭即可。
2.1 打开
打开是在新建的时候完成的,本类提供了2个构造函数,分别是
// 需要写入的文件名
TextReader(String filename)
// 与上一个相比,增加了字符体,包括 US-ASCII,ISO-8859-1,UTF-8,UTF-16BE,UTF-16LE 和 UTF-16
TextReader(String filename, String charset)
2.2 读取
读取行只提供了唯一的函数 readLine()
。同时提供了一个变量 EOF
用于判断是否到文件尾。
2.3 关闭
每次读取完成记得调用close()方法关闭打开的文件。
3 应用示例
public static void main(String[] args) throws Exception {
TextReader tr = new TextReader("D:\\data\\text.txt");
while (!tr.EOF) {
System.out.println(tr.readLine());
}
tr.close();
}
4 源代码
package utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
/**
* 日期:2020/02/21
* 作者:郝伟老师
* 描述:提供了按行读取一个文本文件的函数,同时支持不同编码格式。
*
*/
public class TextReader {
public boolean EOF;
String filename;
String cs;
RandomAccessFile raf;
String seperator;
BufferedReader reader = null;
String line = null;
/**
* 从一个文本文件中读取内容,默认编码为UTF8.
*
* @param filepath 文件路径。
* @throws IOException
*/
public TextReader(String filename) throws IOException {
initialize(filename, null);
}
/**
* 从一个文本文件中读取内容。
*
* @param filepath 文件路径。
* @param cs 编码格式,可以使用StandardCharsets表示。
* @throws IOException
*/
public TextReader(String filename, String charset) throws IOException {
initialize(filename, charset);
}
/**
* 初始化函数。
* @param filename 待打开的文件名。
* @param charset 文件集,默认为utf-8
* @throws IOException
*/
private void initialize(String filename, String charset) throws IOException {
this.filename = filename;
this.cs = charset == null || charset.length() == 0 ? "utf-8" : charset;
this.reader = new BufferedReader(new InputStreamReader(new FileInputStream(filename), cs));
this.line = reader.readLine();
this.EOF = line == null;
}
/**
* 读取文件中的一行。
* @return
* @throws IOException
*/
public String readLine() throws IOException {
String s = line;
line = reader.readLine();
EOF = line == null;
return s;
}
/**
* 关闭当前文件。
* @throws IOException
*/
public void close() throws IOException {
reader.close();
}
/**
* 读取指定文件的所有内容。
* @param filename 待打开的文件名。
* @param charset 文件集,默认为utf-8
*/
public static String readAllLines(String filename, String charset) throws IOException{
StringBuilder sb = new StringBuilder();
TextReader tr = new TextReader(filename, charset);
while (!tr.EOF) {
sb.append(tr.readLine());
sb.append("\r\n"); // Linux 可改成 '\n'
}
tr.close();
return sb.toString();
}
}