开始学Java之21 读取文件

好难。。

第一种 Scanner

1
2
3
4
5
6
7
8
9
10
11
12
13
import java.io.*;
import java.util.Scanner;
public class ReadText {
String message;
public static void main(String[] args)throws IOException {
String message;
Scanner scan = new Scanner ( new File("data\\small.txt"));
while (scan.hasNext()){
message = scan.nextLine();
System.out.println(message);
}
}
}

第二种 BufferedReader

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.io.FileReader;
import java.io.BufferedReader;

public class ReadMe {
public static void main(String[] args) throws java.io.IOException {
BufferedReader br = new BufferedReader(new FileReader("data\\small.txt"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
// sb.append(line).append("\n");
sb.append(line);
line = br.readLine();
}
String fileAsString = sb.toString();
System.out.println(fileAsString);

}
}

BufferedReader 的另外一种

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

import java.io.FileReader;
import java.io.BufferedReader;
import java.io.File;

public class ReadAnotherText {
public static void main(String[] args) throws java.io.IOException {
File mytext = new File("data\\small.txt");
FileReader fr = new FileReader(mytext);
// BufferedReader br = new BufferedReader(new FileReader("data\\small.txt"));
BufferedReader br = new BufferedReader(fr);
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
// sb.append(line).append("\n");
sb.append(line);
line = br.readLine();
}
String fileAsString = sb.toString();
System.out.println(fileAsString);

}
}

https://blog.csdn.net/jiangxinyu/article/details/7885518

https://blog.csdn.net/nickwong_/article/details/51502969

https://www.pianshen.com/article/4248140134/

https://zhidao.baidu.com/question/366278084087529692.html

噢噢知道啥是throws IOException 了。。为了安全,方法加上这个代码,调用这个方法时必须要在try{}里面,安全机制啥的,多人开发比较方便?..

评论

:D 一言句子获取中...

加载中,最新评论有1分钟缓存...