[英]Java: BufferedReader not printing out File content on TXT file
我在使用 BufferedReader 讀取文件夾中 txt 文件的內容時遇到問題,該文件夾通過方法showEditFile()
調用,該方法使用帶有來自方法pideNumero.preguntaUno();
它需要一個 int 來遍歷數組位置:
遍歷文件夾“Archivos”的數組。
public static String[] testFiles() {
String endPath = System.getProperty("user.dir");
String separator = File.separator;
String folderPath = endPath + separator + "Archivos";
File carpeta = new File(folderPath);
String[] lista = carpeta.list();
return lista;
}
讀取內容的第一行的方法應該是Hellowwwww :
public static void showEditFile() throws IOException {
System.out.println("Por Favor, elige un archivo con su numero para mostrar su contenido ");
System.out.println("Los archivos dentro la carpeta Archivos son: ");
Menu.listFiles.nomFiles();
String[] archivos = Menu.listFiles.testFiles();
int menu = Menu.pideNumero.preguntaUno();
File document = new File(archivos[menu - 1]);
try {
FileReader fr = new FileReader(document);
BufferedReader br = new BufferedReader(fr);
String line;
line = br.readLine();
System.out.println(line);
} catch (FileNotFoundException e) {
System.out.println("File not found." + document.toString());
} catch (IOException e) {
System.out.println("Unable to read file: " + document.toString());
}
}
我試圖在調試模式下檢查並在線查看FileReader fr = new FileReader(document);
它會使用 FilePath == null直接跳入 FileNotFoundException,我認為這是問題所在。
似乎它不知道“Archivos”之后的路徑
路徑:根\Archivos\kiki.txt
我已經堅持了一整天了,有人可以幫忙嗎!
carpeta.list()
沒有給出完全限定的路徑。 它只給你文件名。 所以下一次調用new File(archivos[menu - 1])
將失敗。 在new File(archivos[menu - 1])
中,您需要提供完整的,然后您將不會得到異常。 參考https://docs.oracle.com/javase/7/docs/api/java/io/File.html#list()
所以感謝@Jags,我解決了這個問題。 解決方案如下:
在我的數組中,我返回了一個基本上保存字符串的 String[]...沒有分配給它的文件路徑,因為它只是一個字符串)。
我在這里所做的更改:
public static File[] testFiles() {
String endPath = System.getProperty("user.dir");
String separator = File.separator;
String folderPath = endPath + separator + "Archivos";
File carpeta = new File(folderPath);
// here as you can see i used the listFiles() method to list all the files and
// and save them into the File[] array
File[] lista = carpeta.listFiles();
return lista;
}
現在在我的另一個方法 showEditFiles() 中調用該方法時:
public static void showEditFile() throws IOException {
System.out.println("Por Favor, elige un archivo con su numero para mostrar su contenido ");
System.out.println("Los archivos dentro la carpeta Archivos son: ");
Menu.listFiles.nomFiles();
File[] archivos = Menu.listFiles.testFiles();
int menu = Menu.pideNumero.preguntaUno();
File document = new File(archivos[menu - 1]);
try {
FileReader fr = new FileReader(document);
BufferedReader br = new BufferedReader(fr);
String line;
line = br.readLine();
System.out.println(line);
} catch (FileNotFoundException e) {
System.out.println("File not found." + document.toString());
} catch (IOException e) {
System.out.println("Unable to read file: " + document.toString());
}
}
現在它打印出文件的第一行(在本例中是hello)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.