Insert brackets at specific spots in file

225 views Asked by At

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?

2

There are 2 answers

2
Tresdon On BEST ANSWER

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!

0
Soggiorno On

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 are done manipulating it just write it to your file, overwriting the original content.

 FileUtils.writeStringToFile(myFile, fileContents, "utf-8", false);