0

I am trying to remove a specific string in my text file. Current code gets the line one by one until 50 is hit. I am trying to remove the string (EXACT MATCH!) in the notepad, but not sure how to do so.

Scanner input = new Scanner(new File("C:\\file.txt"));
            int counter = 0;
            while(input.hasNextLine() && counter < 50) {
                counter++;
                String tempName = input.nextLine();
                //perform my custom code here
                //somehow delete tempName from the text file (exact match)
            }

I have tried input.nextLine().replaceFirst(tempName, ""); without any luck

beastil34
  • 3
  • 2

2 Answers2

0

If you are using Java 8, You can do something like below using java.nio package:

Path p = Paths.get("PATH-TO-FILE");
List<String> lines = Files.lines(p)
              .map(str -> str.replaceFirst("STRING-TO-DELETE",""))
              .filter(str -> !str.equals(""))
              .collect(Collectors.toList());
Files.write(p, lines, StandardCharsets.UTF_8);
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Tarun
  • 685
  • 3
  • 16
0

Below line replaces "the" with "**"

Pattern pattern = Pattern.compile("the", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(tempName);
String repalcedvalue = matcher.replaceAll("**");
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197