1.利用 java.util.Scanner 这个工具,读取文本文件还是比较简单,只需要利用该类的一个构造方法 Scanner(File file),即可,需要传入一个文件对象,当然这就需要利用 java.io.File了,File file = new File(String location);这里需要传入一个文件的地址;
-
2.文件相对位置、绝对位置
在File构造方法中需要传入文件地址,
(1).文件相对位置,相对与java项目的位置,如
我们需要读取 test.txt 文件的话,则 File file = new File(src/resource/test.txt);
(2)绝对位置
如果想要读取F盘下work 目录下的test.txt 文件,则 File file = new File(“F:\work\test.txt”); -
3.处理读取的内容
读取文本文件的内容是比较简单的,获取内容也比较简单,但是处理一些比较特殊的数据,还是比较麻烦。例如:奇偶行的数据有不同作用,需要分别处理,里面有int类型数据,还有String类型数据,每行中的每个数据之间可能有一个空格,多个空格。这样就只能采用一行一行的读取数据,再处理,不能直接使用 Scanner 对象的next(),nextInt(),等等的方法。 -
4.nextLine()处理数据(split(“\s{1,}”):将多个空格当作一个空格)
需求:从一个文件中读取数据,需要将奇数行、偶数行的数据分别存放到不同的数组中,而且,奇数行获取偶数行中每个数据中间空格数不同。数据格式: 1 23 23 32 32 43 21 23 3 43 2 3 2 43 23 1 2 3 4 5 9 8 1 2 3 6 3 4 88 99 99
- 1
- 2
- 3
- 4
- 5
- 6
- 7
代码实现: package com.daxiong.day4; import java.io.File; import java.util.Scanner; // 相对文件读取处理 public class FileReader { public static void main(String[] args) throws Exception { fileReader("src/resource/test.txt"); } public static void fileReader(String fileName) throws Exception { File file = new File(fileName); Scanner sc = new Scanner(file); int rows = 1; // 记录行数 String[] odd = new String[40]; // 奇数行数据 String[] even = new String[40]; // 偶数行数据 while (sc.hasNextLine()) { if ((rows % 2) == 1) { // 奇数行 odd = sc.nextLine()***.split("\\s{1,}")***; // split("\\2{1,}");不论字符中间有多少个空格都当作一个空格处理 System.out.println("奇数行:" + rows); for (int i = 0; i < odd.length; i++) { System.out.println(odd[i]); } } else if ((rows % 2) == 0) { // 偶数行 even = sc.nextLine().***split("\\s{1,}***"); System.out.println("偶数行:" + rows); for (int i = 0; i < even.length; i++) { System.out.println(even[i]); } } rows++; } sc.close(); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43