import java.io.File;
import java.io.IOException;
import java.util.*;
//import java.lang.Object;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class AppendTool {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Input Directory to Append Values: ");
String dirInput = sc.nextLine();
System.out.println("Input value to append to Directory Files: ");
String valInput = sc.nextLine();
sc.close();
Path source = Paths.get(dirInput);
File path = new File(dirInput);
File [] files = path.listFiles();
for (int i = 0; i < files.length; i++){
if (files[i].isFile()){ //this line weeds out other directories/folders
System.out.println(files[i]);
try {
// int where = files[i].getName().lastIndexOf(".");
String result = valInput + files[i].getName();//.substring(0, where) + files[i].getName().substring(where);
System.out.println(result);
File dest = new File(result);
//Files.move(files[i].toPath(), dest.toPath().resolveSibling(dest.getName()), StandardCopyOption.REPLACE_EXISTING);
Files.move(source, source.resolveSibling(dest.getName()), StandardCopyOption.REPLACE_EXISTING);
System.out.println(dest);
return;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I'm trying to iterate through all files in a directory and append a value to each filename. Using Files.move creates a FileSystemException and states that the file is being used by another process. Using the commented-out Files.move(files[i].toPath.....) deletes creates the new file, deletes the old one from the directory, but it does not replace the original file. Any help would be appreciated. For the error below, I have a stuff.txt file saved in documents and I wanted to append "e" to the filename.
C:\Users\Bob\Documents -> C:\Users\Bob\estuff.txt: The process cannot access the file because it is being used by another process
at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:92) at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103) at java.base/sun.nio.fs.WindowsFileCopy.move(WindowsFileCopy.java:395) at java.base/sun.nio.fs.WindowsFileSystemProvider.move(WindowsFileSystemProvider.java:292) at java.base/java.nio.file.Files.move(Files.java:1426) at AppendTool.main(AppendTool.java:36)