可以使用Java的File类来读取当前路径下的文件。以下是一个简单的示例代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
File file = new File(".");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + file.getAbsolutePath());
}
}
}
在上面的代码中,我们首先创建一个File对象,将当前路径作为参数传入。然后使用Scanner类来读取文件内容,并打印每一行。如果文件不存在,则会捕获FileNotFoundException并输出错误信息。
需要注意的是,这里使用的是相对路径“.”表示当前路径,你也可以使用绝对路径或者其他相对路径来读取指定文件。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:java怎么获取当前路径