Java文件按歌手分类复制功能异常问题求助
Let's walk through the issues in your code and fix them one by one:
Key Problems in the Original Code
1. Broken Artist Name Extraction
Line 16 has an off-by-one error:
String new_name=name.substring(0, name.indexOf("-")-1);
For a filename like Red-Already over, name.indexOf("-") returns 3 (the index of the -). Subtracting 1 makes the end index 2, so you get Re instead of Red. Remove the -1 to get the full artist name.
2. Incorrect Copy Target Path
Right now, you're trying to copy the file directly to the artist directory path (e.g., C:\Output\Red), which is wrong—this would try to overwrite the directory with the file, causing errors. Instead, you need to:
- Extract the song name (everything after the
-) - Copy the file to the artist directory, using the song name as the new filename.
3. mkdir() Fails for Missing Parent Directories
dir.mkdir() only creates a single directory. If your target_path (like C:\Output) doesn't exist yet, this call will fail. Use mkdirs() instead—it creates all missing parent directories automatically.
4. No Null Check for listFiles()
f.listFiles() returns null if the source directory doesn't exist or you don't have access to it. Skipping this check will cause a NullPointerException when you try to loop through total_file.
Fixed Code
Here's the corrected version with comments explaining the changes:
import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; public class OrgLogic { String path = "C:\\Users\\Fawkes\\Music\\Music\\"; String target_path = "C:\\Output\\"; OrgLogic() throws IOException { File sourceDir = new File(path); File rootTargetDir = new File(target_path); // Create root output directory (and parents if needed) rootTargetDir.mkdirs(); // Check if source directory is valid before proceeding File[] totalFiles = sourceDir.listFiles(); if (totalFiles == null) { System.err.println("Source directory doesn't exist or is not accessible."); return; } for (File file : totalFiles) { // Skip directories (only process files) if (!file.isFile()) continue; String fileName = file.getName(); int dashIndex = fileName.indexOf("-"); // Skip files that don't follow the Artist-Song format if (dashIndex == -1) { System.out.println("Skipping file with invalid format: " + fileName); continue; } // Extract artist name and song name correctly String artistName = fileName.substring(0, dashIndex); String songName = fileName.substring(dashIndex + 1); // Create artist directory (mkdirs handles existing directories gracefully) File artistDir = new File(rootTargetDir, artistName); artistDir.mkdirs(); // Define the full target file path File targetFile = new File(artistDir, songName); // Copy the file, replacing existing files if needed Files.copy(file.toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } } public static void main(String[] args) { try { new OrgLogic(); } catch (IOException e) { e.printStackTrace(); } } }
Additional Improvements
- Added checks to skip directories and files that don't match the
Artist-Songformat - Used enhanced for-loop for cleaner iteration over files
- Renamed variables for better readability (e.g.,
total_file→totalFiles) - Made error handling more explicit for invalid source directories
内容的提问来源于stack exchange,提问作者Fawkes




