方法一:
/** * 按流读取文件 * @param path * @return * @throws FileNotFoundException */ public static BufferedReader openFile(final String path) throws FileNotFoundException { FileInputStream in = new FileInputStream(new File(path)); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); return reader; }
方法二(推荐):
/** * 读到缓冲区 * @param path * @return * @throws FileNotFoundException */ public static BufferedReader openFile(final String path) throws FileNotFoundException { BufferedReader reader = new BufferedReader(new FileReader(path)); return reader; }
按行读取:
read.readLine(); // 这里返回的不是数组,而是字符串String
读取完了别忘了关闭:
reader.close();
读取前K行(获取所有行原理一样):
public String[] readKlines(BufferedReader reader, final int k) throws IOException {
String[] lines = new String[k]; for (int i = 0; i < k; i++) { lines[i] = reader.readLine(); // 建议加个判断版空行去除 reader.readLine() != null }
reader.close(); // 记得关闭文件流!!! return lines; }
获取行数:
/** * 获取行数 * @param reader * @return * @throws IOException */ public int getNumLines(BufferedReader reader) throws IOException { int numLines = 0; while(reader.readLine() != null) { numLines += 1; }
reader.close(); // 记得关闭文件流!!! return numLines; }
参考:
http://www.homeandlearn.co.uk/java/read_a_textfile_in_java.html