Java 逐行读取文件 - 代码示例及常见问题解决
import java.io.*;
public class ReadFileLineByLine {
public static void main(String[] args) {
// 获取用户输入的文件路径和文件名
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println('请输入文件路径和文件名:');
String filePath = null;
try {
filePath = br.readLine();
} catch (IOException e1) {
e1.printStackTrace();
}
File file = new File(filePath);
// 尝试读取文件并逐行输出到控制台
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
'为啥拒绝访问内容:这可能是由于文件权限设置问题导致的。当一个文件被设置为仅限某个用户或用户组访问时,其他用户或用户组将无法访问该文件,从而导致拒绝访问错误。解决方法是检查文件的权限设置,确保当前用户有访问该文件的权限。或者,可以尝试使用管理员权限运行程序来访问该文件。'
原文地址: https://www.cveoy.top/t/topic/oQ3X 著作权归作者所有。请勿转载和采集!