I am looking for a match in the file with the entered string. Next I need to change the found string to the one entered for the replacement. The search did:

private void handleButtonAction3(ActionEvent event) throws FileNotFoundException, IOException { String searchWord = scrfield.getText(); String changeWord = chngfield.getText(); byte[] content; try (FileInputStream fis = new FileInputStream(file);) { content = new byte[fis.available()]; fis.read(content); } String[] lines = new String(content).split("\n"); int i = 1; for (String line : lines) { String[] words = line.split(" "); int j = 1; for (String word : words) { if (word.equalsIgnoreCase(searchWord)) { ansarea.appendText("Found: "+word+"\n"); //замена ansarea.appendText("Replaced successfully."); find = true; } j++; } i++; }if(find == false) ansarea.appendText("Совпадений не найдено! \n Nothing to change!"); } 
  • one
    What is the question? - Dmitry
  • how to replace the found string with the entered one and write to the file instead of the old one. - George Lu

2 answers 2

 private void handleButtonAction3(ActionEvent event) throws IOException { String searchWord = scrfield.getText(); String changeWord = chngfield.getText(); StringBuilder sb = new StringBuilder(); try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) { String strLine; while ((strLine = br.readLine()) != null) { sb.append(strLine.replace(searchWord, changeWord)).append("\r\n"); } } try (FileWriter fileWriter = new FileWriter(file)) { fileWriter.write(sb.toString()); } } 
  • I specifically show 2 ways - through streams using buffering, as well as through FileWriter. Accordingly, you can read using FileReader and record using streams. There is someone you like - Dmitry

There is an excellent method String.replace () that will help you if you need to replace the first substring found.

If the required substrings are many and you need to replace everything, then you can use String.replaceAll ()


In your case, if the register is important and simply adding your code can be

 for (String line : lines) { String[] words = line.split(" "); for (int i = 0; i<words.length; i++) { if (words[i].equalsIgnoreCase(searchWord)) { ansarea.appendText("Found: "+word+"\n"); //замена words[i] = changeWord; ansarea.appendText("Replaced successfully."); find = true; } } } 
  • System.out.print (line + "\ n"); line.replace (line, changeLine); System.out.print (line); Gives in the conclusion: eight boys eight boys, and should in the second case be eight toys - George Lu
  • replace is sensitive to the registr - Victor