Reputation: 721
I am trying to move some MP3 files to different folders using File.renameTo()
, however it just keeps not working I don't know why.
Can you tell me what am I doing wrong, please?
File songsFolder = new File("songs");
File[] songsList = songsFolder.listFiles();
for (int i = 0; i < allSongs.size(); i++) {
//allSongs is an ArrayList defined earlier
File music = (File) songsList[i];
FileInputStream fileMusic = new FileInputStream(music);
int size = (int) music.length();
fileMusic.skip(size - 128);
byte[] last128 = new byte[128];
fileMusic.read(last128);
String id3 = new String(last128);
String tag = id3.substring(0, 3);
if (musicsList[i].isFile()) {
File afile = songsList[i];
if (afile.renameTo(new File("songs/" + id3.substring(33, 62).trim() + "/" + songsList[i].getName()))) {
System.out.println("File moved successfully!");
} else {
System.out.println("File failed to move!");
}
}
}
The output is:
File failed to move!
File failed to move!
File failed to move!
File failed to move!
Upvotes: 0
Views: 525
Reputation: 25390
Does the directory "songs/" + id3.substring(33, 62).trim()
already exist? File.renameTo()
will not create the directory for you.
Try something like this:
File afile = songsList[i];
File newDir = new File("songs", id3.substring(33, 62).trim());
newDir.mkdirs();
File newName = new File(newDir, afile.getName());
afile.renameTo(newName);
Upvotes: 1
Reputation: 298153
You have to close FileInputStream
s before attempting to rename the associated files. You should generally close such resource when done with it.
Further, you should check whether the target directory really exists.
If you are programming under Java 7 you should try the new java.nio.file API. This offers a move method throwing an exception telling you more about the reason instead of just returning false
.
Upvotes: 0