There are two txt files. In the first one there is a list of the necessary lines, in the second one there is a large accumulation of random nonsense from which you need to take the lines starting the same as the lines in the first file.

Contents of the first (list):

test test1 test2 

Contents of the second (all):

 test test1 .02 test4 .03 

Actually, I just can’t implement a method for solving the task, displays only the very first line, which is no different. Please help and advice. The result should output this:

 test test1 .02 ///строчку test4 .03 не выведет, так как её нет в содержимом первого файла. 

I enclose my code:

 ArrayList<String> fin = new ArrayList<>(); ArrayList<String> fin2 = new ArrayList<>(); Scanner sc1 = new Scanner(new FileReader("C:\\1\\list.txt")); Scanner sc2 = new Scanner(new FileReader("C:\\1\\all.txt")); while (sc1.hasNext()){ String str = sc1.nextLine(); fin.add(str); while(sc2.hasNext()){ String str2 = sc2.nextLine(); if(str2.startsWith(fin.get(fin.size()-1))){ fin2.add(str2); } } } 
  • Decide on the string selection criteria. If, as you say, нужно взять строки, начинающиеся так же , then the line test4 .03 will be selected, since it starts with test . - post_zeew

1 answer 1

In the first one there is a list of the necessary lines, in the second one there is a large accumulation of random nonsense from which you need to take the lines starting the same way as the lines in the first file.

Under this condition, the string test4 .03 will be valid, as it begins with the word test .

If I understand you correctly, the criterion for selecting a line is somewhat different. A string is considered valid if the first word in it matches one of the words in the first file.

Assuming this criterion, you can write this bike:

 public class Main { public static void main(String[] args) throws IOException { ArrayList<String> list = getArrayListFromFile("list.txt"); ArrayList<String> all = getArrayListFromFile("all.txt"); System.out.println("list: " + list); System.out.println("all: " + all); deleteStrings(list, all); System.out.println("\nAfter removing:"); System.out.println("all: " + all); } private static void deleteStrings(ArrayList<String> list, ArrayList<String> all) { Iterator<String> it = all.iterator(); while (it.hasNext()) { String currentLine = it.next(); String firstWord = currentLine.split("\\s+")[0]; if (!list.contains(firstWord)) it.remove(); } } private static ArrayList<String> getArrayListFromFile(String fileName) throws IOException { ArrayList<String> arrayList = new ArrayList<String>(); BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName)); String sCurrentLine; while ((sCurrentLine = bufferedReader.readLine()) != null) { arrayList.add(sCurrentLine); } bufferedReader.close(); return arrayList; } } 

The output to the console which will be:

 list: [test, test1, test2] all: [test, test1 .02, test4 .03] After removing: all: [test, test1 .02] 

Ps. Exception handling is yours.