问题
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!
回答1:
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:
- 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.
回答2:
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.
来源:https://stackoverflow.com/questions/27275272/replacing-tab-characters-in-java-files-with-4-spaces