java - 无法将 MP3 文件移动到其他文件夹

标签 java file-rename

我尝试使用 File.renameTo() 将一些 MP3 文件移动到不同的文件夹,但它一直无法工作,我不知道为什么。

你能告诉我我做错了什么吗?

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!");
        }
    }
}

输出为:

File failed to move!
File failed to move!
File failed to move!
File failed to move!

最佳答案

目录"songs/"+ id3.substring(33, 62).trim()已经存在吗? File.renameTo() 不会为您创建目录。

尝试这样的事情:

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

关于java - 无法将 MP3 文件移动到其他文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18486572/

相关文章:

java - 在 jTable 中选择一行会生成错误

ios - 在 iOS 中重命名类

regex - 使用 perl oneliner 重命名匹配文件时出错

java - 连接到 Firebird 数据库时出现错误 "Insufficient memory to allocate page buffer cache"

java - 如何知道锁已被获取

java - 如何摆脱嵌套的 RxJava 流?

java - 由于文件重命名导致输入更改时更改编辑器上的标题

java - 如何使用 TortoiseGit 提交区分大小写的重命名文件?

wget - 使用 wget 覆盖文件但使用临时文件名直到收到完整文件,然后重命名

java - Axis2转换xs :boolean to java Boolean