0

I wanted to remove the spaces that Windows puts in filenames. I ran the following code to rename all the files in a test directory thus. The result: all the files disappeared. I am puzzled as to why.

import java.io.*; public class FileRenamer { public static void main(String[] args) { for (File file: (new File("O:\\test0")).listFiles()) file.renameTo(new File(file.getName().replaceAll("\\s",""))); System.exit(0); } } 
3
  • You are right this should delete any files. It could move them to another directory. Commented Feb 11, 2016 at 0:22
  • 2
    Just to be clear, these are not "the spaces that Windows puts in filenames". These are spaces that you put in Windows filenames. Windows itself doesn't add spaces to your filenames. Could your answer therefore be a simpler one: don't put spaces in your filenames in the first place? Commented Feb 11, 2016 at 0:41
  • 1
    No, I did a bulk rename in Windows Explorer. I selected all the files in a directory, pressed F2 (which highlighted the main part of the filename (before the dot)) and typed "test", then pressed Enter. Windows renamed them "test (1).png", "test (2).png", etc. Note the space before the "(". Commented Feb 11, 2016 at 0:50

2 Answers 2

2

TL;DR: You are moving the file.

You list the files in a directory "O:\\test0.

For each such file you then create a String:

file.getName().replaceAll("\\s","") 

You end up with:

new File("someFileName") 

So you have called:

file.renameTo(new File("someFileName")) 

Now, someFileName is not an absolute path; but a relative path. So you have moved from O:\\test0\\some File Name to someFileName, where someFileName is in the directory of the program.

P.S. there is no need to call System.exit(0).

Sign up to request clarification or add additional context in comments.

1 Comment

I think that you missed the call to File.listFiles(), he's not renaming the directory but the files inside the directory. But agree that the OP is moving the files to the current working directory
0

Yes, I found the files had been moved to my class file directory.

Boris's tip about relative vs. absolute paths showed me the solution: to use the

public File(File parent, String child) 

constructor for the new abstract File object. The following code did the job correctly.

import java.io.*; public class FileRenamer { public static void main(String[] args) { File dir = new File("O:\\test0"); for (File file: dir.listFiles()) file.renameTo(new File(dir, file.getName().replaceAll("\\s",""))); } } 

1 Comment

Even better, don't use the outdated and crappy Java IO library, but the new and much better Java NIO library.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.