I am trying to make a program that receives a specified String
, and removes every occurence of this String
in a text document. The text file that is used to read / write is the same. The arguments used are received from cmd, in this order:
inputString filename
The program compiles fine, but after running it leaves the original text file blank. If i make a try-catch block for input handling, and a try-catch block for output handling, I am able to read and write to the same file. If i use a try-with-resources block, I am able to read a file, and save the output to a different file than the original, with all occurences of inputString
from cmd removed. But it seems like I can't read and write to the same file using try-with-resources, and also the input.hasNext()
statement returns false when I try to do it this way.
Code example below:
package ch12;
import java.io.*;
import java.util.*;
public class Chapter_12_E11_RemoveText {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("Usage java ch12.Chapter_12_E11_RemoveText inputString filename");
System.exit(1);
}
File filename = new File(args[1]);
if (!filename.exists()) {
System.out.println("Target file " + args[1] + " does not exist");
System.exit(2);
}
try (
Scanner input = new Scanner(filename);
PrintWriter output = new PrintWriter(filename);
) {
System.out.println("hasNext() is " + input.hasNext());
System.out.println("hasNextLine() is " + input.hasNextLine());
while (input.hasNext()) {
String s1 = input.nextLine();
System.out.println("String fetched from input.nextLine() " + s1);
System.out.println("Attemping to replace all words equal to " + args[0] + " with \"\"");
String s2 = s1.replaceAll(args[0], "");
output.println(s2);
}
}
}
}
I am suspecting that when I create a new PrintWriter
object with the argument filename
, the original file is overwritten by a blank file before the while-loop
executes. Am i right here? Is it possible to read and write to the same file using try-with-resources?