java 读取txt
在Java中读取txt文件有多种方式,常用的方法包括使用BufferedReader
、FileReader
和Files
类。下面是几种常见的方法来读取txt文件的示例代码。
方法一:使用 BufferedReader
和 FileReader
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
String filePath = "path/to/your/file.txt";
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
方法二:使用 Files
类(Java 7 及以上)
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
String filePath = "path/to/your/file.txt";
try {
List<String> lines = Files.readAllLines(Paths.get(filePath));
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
方法三:使用 Scanner
类
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFileExample {
public static void main(String[] args) {
String filePath = "path/to/your/file.txt";
try (Scanner scanner = new Scanner(new File(filePath))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
在上述示例中,path/to/your/file.txt
应替换为你实际的txt文件路径。
注意事项
- 文件路径:确保路径正确且文件存在。
- 异常处理:文件读取过程中可能会出现IO异常,需要进行适当的处理。
- 编码:如果文件有特定的编码,如UTF-8,可能需要指定编码格式进行读取。
- 资源管理:要确保文件资源在读取完毕后正确关闭,推荐使用
try-with-resources
语句处理可关闭的资源。
选择适合你需求的方法来读取文件内容。如果你需要处理大文件,使用BufferedReader
可能会更有效率,因为它是基于缓冲的读取。