In general it's not really possible to write to a specific location in a file due to the way file systems are set up. A RandomAccessFile
can accomplish the task in some cases but generally you'll want an input stream like a Scanner
and an output stream like a PrintWriter
to rewrite the file line by line. It can be implemented roughly like this:
Scanner in = new Scanner(new File("test.txt"));
PrintWriter out = new PrintWriter(new File("out.txt"));
String searchFor = "require(";
while(in.hasNextLine()){
String tmp = in.nextLine();
if(tmp.contains(searchFor)){
String result;
int index = tmp.indexOf(searchFor) + searchFor.length()+1;
int endIndex = tmp.indexOf("\"",index);
String first = tmp.substring(0, index);
String word = tmp.substring(index, endIndex);
result = first + "[" + word + "]\")";
out.println(result);
}
else{
out.println(tmp);
}
}
out.flush();
This accomplishes the task by looking line by line and seeing if the line needs to be adjusted or if it can just be kept the same, and it makes a new file with the changes.
It can also overwrite the file if the arguments in the Scanner and PrintWriter are the same. Hope this helps!