I've had a search about here, and nothing seems to be on the topic of replacing tab characters, I was wondering if anybody can suggest to me any easy ways to replace the tab characters with 4x 'space' characters in over 5,000 files! The files are .java
files on an SVN server.
I can think of some ways using java (the language i am most comfortable with) to read in the file and replace that way, but I am sure there is probably an easier way of doing this!
If you are familiar with
Java 7
, it has greatly improvedNIO
package. Reading/writing and accessing files from directories has become very easy. You should give it a go.It is possible of course. But you need to know what encoding those files are in.
Quick solution using the shell, provided this is a Unix system (if Windows, well, install cygwin):
Done.
With Java, well, I do hope you are using Java 7+. If yes this is quite easy: use
Files.walkFileTree()
, collect all regular files into aList
for instance, and when you have that, perform substitution on each file in the list. DO NOT do this in theFileVisitor
itself, you might get aDirectoryIteratorException
.Links which can help:
SimpleFileVisitor
;Files.walkFileTree()
;Files.newBufferedReader()
;Files.newBufferedWriter()
.Also, and very importantly, DO NOT MODIFY THE FILES INLINE. This will not work. Create a temporary file, write the new contents in it, then rename to the original.
Conceptually there's no easier way but to open the files, search for tabs,
and replace each one of them with 4 space characters as you need. How do you
do it exactly: this is entirely up to you.
In Eclipse you can reformat all your project files at once. Right click on your root package, and go to Source -> Format.
Try this:
Use:
And then:
String newFileContent = fileContent.replaceAll("\t", " ");