- 目标:读取文件
编程时,有很多时候需要读取本地文件,下面介绍一下读取方式:
读单行文件
上代码:
1 package com;
2 import java.io.*;
3 import java.util.ArrayList;
4 import java.util.List;
5
6 import javax.print.DocFlavor.CHAR_ARRAY;
7
8 import com.google.common.primitives.Chars;
9 /*
10 1、首先创建FileReader对象
11 2、将FileReader传递给BufferedReader
12 3、采用BufferedReader的readLine()方法和read()方法来读取文件内容
13 4、最后一定要的finally语句中关闭BufferedReader15 */
16 public class MathYsf3{
17 public static void main(String[] args){
18 BufferedReader br = null;
19 BufferedReader br2 = null;
20 try {
21 br = new BufferedReader(new FileReader("C:\\Users\\91911\\Desktop\\test.txt"));
22 // 第一种读取文件方式
23 System.out.println("Reading the file using readLine() method: ");
24 String contentLine ;
25 List<String> arr1 = new ArrayList<>();
26 while ((contentLine = br.readLine()) != null) {
27 // contentLine = br.readLine();
28 //读取每一行,并输出
29 System.out.println(contentLine);
30 //将每一行追加到arr1
31 arr1.add(contentLine);
32 }
33 //输出数组
34 System.out.println(arr1);
35 // 第二种读取文件方式
36 br2 = new BufferedReader(new FileReader("C:\\Users\\91911\\Desktop\\test.txt"));
37 System.out.println("Reading the file using read() method: ");
38 int num = 0;
39 char ch;
40 while ((num = br2.read()) != -1) {
41 ch = (char) num;
42 System.out.print(ch);
43 }
44 } catch (FileNotFoundException e) {
45 e.printStackTrace();
46 } catch (IOException e) {
47 e.printStackTrace();
48 } finally {
49 try {
50 if (br != null) {
51 br.close();
52 }
53 if (br2 != null) {
54 br2.close();
55 }
56 } catch (IOException e) {
57 System.out.println("Error in closing the BufferedReader");
58 }
59 }
60 }
61 }
结果输出: