The first loop checks every line from the file and if there are Russian characters and then inserts them into the Map, and the second one should replace the characters in the file that are present in the Map with another text.

public class MainClass { private static Path FILE_PATH = Paths.get("text.txt"); public static void main(String[] args) throws IOException { Map<Integer, Map<Integer, String>> mapFile = new HashMap<>(); List<String> fileContent = new ArrayList<>(Files.readAllLines(FILE_PATH, StandardCharsets.UTF_8)); for (int i = 0; i < fileContent.size(); i++) { Map<Integer, String> mapLine = new HashMap<>(); Pattern p = Pattern.compile("[а-яА-Я]+"); Matcher m = p.matcher(fileContent.get(i)); while(m.find()) { String cutText = fileContent.get(i).substring(m.start(), m.end()); int keyMap = fileContent.get(i).indexOf(cutText); String valueMap = cutText; mapLine.put(keyMap, valueMap); } mapFile.put((i + 1), mapLine); } for (int i = 0; i < fileContent.size(); i++) { String oldLine = fileContent.get(i); Pattern p = Pattern.compile("[а-яА-Я]+"); Matcher m = p.matcher(oldLine); while(m.find()) { String word = oldLine.substring(m.start(), m.end()); int indexWord = fileContent.get(i).indexOf(word); if (indexWord != 0) { String newLine = oldLine.replaceAll(mapFile.get(i+1).get(indexWord), "++++++"); System.out.println("oldLine = " + oldLine); fileContent.set(i, newLine); } } } System.out.println("mapFile : " + mapFile); Files.write(FILE_PATH, fileContent, StandardCharsets.UTF_8); } } 

Mistake:

 Exception in thread "main" java.lang.NullPointerException at java.util.regex.Pattern.<init>(Pattern.java:1350) at java.util.regex.Pattern.compile(Pattern.java:1028) at java.lang.String.replaceAll(String.java:2223) at com.multithreading.fileRead.MainFile.main(MainFile.java:62) 
  • How can you in the second cycle look for a pattern matching on one line, and look for the position of a word from a new line? The new line contains the modified text and if there are two identical words, then at the second match, these words will already be replaced. In general, you can read a word from Match. The index can be read from the additional variable count - Alex78191
  • Nafig associative array to create, if you can immediately replace the text? - Alex78191
  • @ Alex78191 I use words that will be replaced with words from another document, which will correspond and are substituted depending on the index. In order to make an array, it has the line number and the position of the beginning of the word. - Vitalik Andrysha
  • 2
    you have this mapFile.get (i + 1) .get (indexWord); becomes null at ~ 4 iterations. hence the NullPointerException. - Jiraff537

0