Insert parentheses at specific locations in a file
I am trying to write a script that, given a file, will search through it, and every time it encounters a call, parentheses will be added, so for example
var x = require("name")
becomes
var x = require(["name"])
Usually for something like this I would consider using a Scanner, but since I want to edit in a file, I consider FileChannel since from what I've read it can manipulate files. However, I am not sure if this is the most efficient method to achieve this; any advice on how should i do this?
source to share
In general, it is not possible to write to a specific location in a file due to the way the file systems are configured. A RandomAccessFile
can accomplish the task in some cases, but usually you need an input stream such as Scanner
, and an output stream such as PrintWriter
to rewrite the file line by line. It can be implemented 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();
It does the task of looking down the line and seeing if the line needs to be adjusted or it can just be kept the same and it creates a new file with the changes.
It can also overwrite the file if the arguments to Scanner and PrintWriter are the same. Hope this helps!
source to share
Consider using the FileUtils class from the Apache Commons Io library.
String pathToFile = "C:/SomeFile.txt";
File myFile = new File(pathToFile);
String fileContents = FileUtils.readFileToString(pathToFile, "utf-8");
Then you can manipulate the string, and when you're done manipulating it, just write it to your file, overwriting the original content.
FileUtils.writeStringToFile(myFile, fileContents, "utf-8", false);
source to share