public class SearchFiles { static ArrayList<File> FilesFind = new ArrayList<>(); public static void main(String[] args) throws IOException { String mask, search; int count = 0; Scanner DIR_NAME = new Scanner(System.in); Scanner MASK_NAME = new Scanner(System.in); System.out.println("Input name directory :"); getFileslist(DIR_NAME.nextLine()); System.out.println("Input mask :"); mask = MASK_NAME.nextLine(); System.out.println("Find files is :" ); // цикл поиска файла for (File fill : FilesFind) { BufferedReader reader = new BufferedReader(new FileReader(fill)); while ((search=reader.readLine())!= null){ if (search.contains(mask) && !search.isEmpty()){ count++; System.out.println("Name files : " + fill.getName() + " --- > " + " String : " + count); } } reader.close(); } } public static void getFileslist(String nameDirectory){ File f = new File(nameDirectory); for (File s : f.listFiles()) { if (s.isFile()) { FilesFind.add(s); } else if (s.isDirectory()) { getFileslist(s.getAbsolutePath()); } } } } |
1 answer
In your example, the count variable is responsible for the number of lines, but as you can see, at the end of the program this variable is equal to the total number of lines in all files.
In order to calculate separately for each file, you need
int count = 0; replaced by
Map<File,Integer> fileMap = new HashMap<>(); And rewrite the cycle a bit
for (File fill: FilesFind) { BufferedReader reader = new BufferedReader(new FileReader(fill)); int count = 0; while ((search = reader.readLine()) != null) { if (search.contains(mask) && !search.isEmpty()) { count++; System.out.println("Name files : " + fill.getName() + " --- > " + " String : " + count); } } fileMap.put(fill, count); reader.close(); } PS If you don’t need to use the number of lines for each file anywhere else, you can delete the map and simply create the count variable in the for loop
|