Replacing Tab characters in java files with 4 spac

2019-09-04 22:55发布

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!

6条回答
forever°为你锁心
2楼-- · 2019-09-04 23:07

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.

查看更多
Emotional °昔
3楼-- · 2019-09-04 23:09

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.

查看更多
狗以群分
4楼-- · 2019-09-04 23:13

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.

查看更多
仙女界的扛把子
5楼-- · 2019-09-04 23:19

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

查看更多
神经病院院长
6楼-- · 2019-09-04 23:28

Try this:

inputString = inputString.replaceAll("\t", "    ")
查看更多
不美不萌又怎样
7楼-- · 2019-09-04 23:32

Use:

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

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

查看更多
登录 后发表回答