无法使用 FileReader 和 BufferedReader 读取 Java 中的文本文件,可能的原因是什么?
Unable to Read Text File in Java using FileReader and BufferedReader, possible reasons?
这里从 start()
方法我用 text file
调用了 loadMap(filename)
方法。但我不知道为什么虽然调用了 loadMap() 但 FileReader
和 BufferedReader
不起作用。以及在这两个文件 reader 的声明下方评论的文本
System.out.print("INside loadMap()");
不在控制台中打印并且文本文件未读取。这里实际发生了什么问题?请帮助某人。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class DemoClass {
public static void main(String[] args) {
start();
}
public static void start() {
try {
System.out.print("Pobon File Inside");
loadMap("data\map1.txt");
} catch (Exception e) {
// TODO: handle exception
}
}
private static void loadMap(String filename) throws IOException {
ArrayList lines = new ArrayList();
FileReader fReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fReader);
System.out.print("INside loadMap()");
while (true) {
String line = reader.readLine();
if (line == null) {
reader.close();
break;
}
if (!line.startsWith("!")) {
lines.add(line);
}
}
System.out.print("INside loadMap()");
}
}
如果从未调用 System.out.print("INside loadMap()")
,则在创建 FileReader.
时必须抛出 IOException
也就是说,您调用loadMap()
时作为参数输入的文件(data\map1.txt)不存在。您应该考虑以不同的方式检索文件,例如将其放在 源文件夹 中,然后调用 getClass().getResource()
这里从 start()
方法我用 text file
调用了 loadMap(filename)
方法。但我不知道为什么虽然调用了 loadMap() 但 FileReader
和 BufferedReader
不起作用。以及在这两个文件 reader 的声明下方评论的文本
System.out.print("INside loadMap()");
不在控制台中打印并且文本文件未读取。这里实际发生了什么问题?请帮助某人。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class DemoClass {
public static void main(String[] args) {
start();
}
public static void start() {
try {
System.out.print("Pobon File Inside");
loadMap("data\map1.txt");
} catch (Exception e) {
// TODO: handle exception
}
}
private static void loadMap(String filename) throws IOException {
ArrayList lines = new ArrayList();
FileReader fReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fReader);
System.out.print("INside loadMap()");
while (true) {
String line = reader.readLine();
if (line == null) {
reader.close();
break;
}
if (!line.startsWith("!")) {
lines.add(line);
}
}
System.out.print("INside loadMap()");
}
}
如果从未调用 System.out.print("INside loadMap()")
,则在创建 FileReader.
也就是说,您调用loadMap()
时作为参数输入的文件(data\map1.txt)不存在。您应该考虑以不同的方式检索文件,例如将其放在 源文件夹 中,然后调用 getClass().getResource()