I wrote a code to read a files from a directory.
The directory contain many files. Firstly, I count the number of the files in the directory, then I would like to count number of lines in the files that have as extension: .info
and .data
My code is the following:
public void checkEmptyEntryFileLoader(String directory) { File name = new File(directory); String filenames[]=name.list(); long countFile = 0; long countLineData = 0; long countLineInfo = 0; for(String filename:filenames){ //System.out.println(filename); countFile++; } System.out.println(countFile); // this bloc worked well File files[]=name.listFiles(); for(File file:files){ String fileName = file.getName(); if(fileName.endsWith("data")) { try { BufferedReader reader = new BufferedReader(new FileReader(fileName)); while (reader.readLine() != null) { countLineData++; } }catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } if(fileName.endsWith("info")) { try { BufferedReader reader = new BufferedReader(new FileReader(fileName)); while (reader.readLine() != null) { countLineInfo ++; } }catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } System.out.println(countLineInfo ); } }
I got as error:
java.io.FileNotFoundException: my_file_name.data (No such file or directory) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(FileInputStream.java:195) at java.io.FileInputStream.<init>(FileInputStream.java:138) at java.io.FileInputStream.<init>(FileInputStream.java:93) at java.io.FileReader.<init>(FileReader.java:58)
The error concerns the FileReader
, it accept only the string
, and the filename
is a String
Do you have some idea please ? Thank you
Advertisement
Answer
Instead of passing filename
in FileReader()
, try passing file
.
BufferedReader reader = new BufferedReader(new FileReader(file));
My answer assumes that the error that you have given as output is stack trace printed in the try-catch block and not the error that you get when you try to compile/run the code.