Eclipse 读取文件
在 Eclipse 中读取文件是一种常见的操作,有两种主要方法:
1. FileInputStream
用法:
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
import java.io.FileInputStream;
import java.io.IOException;
public class ReadFileWithFileInputStream {
public static void main(String[] args) {
String filename = "my_file.txt";
try {
// 创建 FileInputStream 对象
FileInputStream in = new FileInputStream(filename);
// 读取文件内容并打印到控制台
int ch;
while ((ch = in.read()) != -1) {
System.out.print((char) ch);
}
// 关闭文件流
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. Scanner
用法:
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
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFileWithScanner {
public static void main(String[] args) {
String filename = "my_file.txt";
try {
// 创建 Scanner 对象
Scanner scanner = new Scanner(new File(filename));
// 读取文件内容并打印到控制台
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
// 关闭文件流
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
以上就是eclipse怎么读取文件的详细内容,更多请关注其它相关文章!