我刚刚读完了另一个相同类型的问题,但不幸的是它并没有给我很多帮助。
我在将mp3和jpg等文件移动到我尝试移动这些文件之前创建的另一个文件夹时遇到问题。
这是我的代码:
public class FilesSorter {
private String extension;
public FilesSorter(String ext) {
this.setExtension(ext);
}
public void setExtension(String extension) {
this.extension = extension;
}
public void sortIt(Path path, Path FileName) {
String StringPath = path.toString();
switch (this.extension) {
case "folder":
return;
case "txt":
File folderDocs = new File(StringPath + ("\\Documents"));
if (!folderDocs.exists()) {
folderDocs.mkdir();
}
Path sourceDocs = path.resolve(FileName);
Path targetDocs = folderDocs.toPath().resolve(FileName);
try {
Files.move(sourceDocs, targetDocs, ATOMIC_MOVE);
} catch (IOException e) {
System.out.println("Moving failed.");
}
break;
case "mp3":
case "wma":
case "ogg":
File folderMsc = new File(StringPath + ("\\Music"));
if (!folderMsc.exists()) {
System.out.println("created folder");
folderMsc.mkdir();
}
Path sourceMsc = path.resolve(FileName);
Path targetMsc = folderMsc.toPath().resolve(FileName);
System.out.println(sourceMsc);
System.out.println(targetMsc);
try {
Files.move(sourceMsc, targetMsc, REPLACE_EXISTING);
} catch (IOException e) {
System.out.println("Moving failed.");
}
break;
...
}
我称之为该方法的片段:
while (true) {
key = FolderMonitor.take();
Kind<?> tmp;
for (WatchEvent<?> EventsInFolder : key.pollEvents()) {
tmp = EventsInFolder.kind();
if (tmp == ENTRY_CREATE) {
Path RecentlyCreatedPath = ((WatchEvent<Path>) EventsInFolder).context();
System.out.println("New Path created: " + RecentlyCreatedPath);
type = this.giveMeType(String.valueOf(RecentlyCreatedPath));
this.actWithFile(type, RecentlyCreatedPath);
} else if (tmp == ENTRY_DELETE) {
System.out.println("Path deleted: " + ((WatchEvent<Path>) EventsInFolder).context());
} else if (tmp == OVERFLOW) {
continue;
}
}
if (!key.reset()) {
break;
}
timeThen = System.currentTimeMillis();
if(timeThen - timeNow > 120000) {
break;
}
}
正如我所说的那样,当我尝试移动txt时,它会起作用,当我尝试移动mp3时,它会说&#34;移动失败。&#34;
提前感谢大家回答我的问题,或提供一些其他提示,以便在哪里找到这些信息。
编辑:这是我实际调用sortIt方法的代码(很抱歉没有提前完成)。
private void actWithFile (String type, Path pathToFile) {
FilesSorter fs = new FilesSorter(type);
fs.sortIt(this.PathDirectory, pathToFile);
}