I'm trying to write a script that, given a file, will search through it and every time it encounters a require call will add brackets, so that, for instance,
var x = require("name")
becomes
var x = require(["name"])
Normally for something like this I'd consider using Scanner, but since I want to edit in the file I'm considering FileChannel since from what I've read it can manipulate files. However I'm unsure if this is the most efficient method of accomplishing this; any tips on how I should go about this?
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 aScanner
and an output stream like aPrintWriter
to rewrite the file line by line. It can be implemented roughly like this: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!