Soaps
Soaps

Reputation: 1

Replacing Tab characters in java files with 4 spaces?

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!

Upvotes: 0

Views: 6258

Answers (6)

peter.petrov
peter.petrov

Reputation: 39457

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.

Upvotes: 1

Jase Pellerin
Jase Pellerin

Reputation: 397

Try this:

inputString = inputString.replaceAll("\t", "    ")

Upvotes: -1

fge
fge

Reputation: 121750

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):

find thedir -type f -exec perl -pi -e 's,\t,    ,g' {} \;

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 a List for instance, and when you have that, perform substitution on each file in the list. DO NOT do this in the FileVisitor itself, you might get a DirectoryIteratorException.

Links which can help:


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.

Upvotes: 1

Darshan Mehta
Darshan Mehta

Reputation: 30829

If you are familiar with Java 7, it has greatly improved NIO package. Reading/writing and accessing files from directories has become very easy. You should give it a go.

Upvotes: 0

javaHunter
javaHunter

Reputation: 1097

Use:

String fileContent = new Scanner(new File("file.txt")).useDelimiter("\\Z").next();

And then: String newFileContent = fileContent.replaceAll("\t", " ");

Upvotes: 0

vz0
vz0

Reputation: 32923

In Eclipse you can reformat all your project files at once. Right click on your root package, and go to Source -> Format.

Upvotes: 0

Related Questions