Friday, July 28, 2017

Windows - Unable to delete file with name too long

Problem :

In Eclipse while moving some packages to another it accidently got copied several times. Not sure how. It created a folder under folders like infinite times.

Apparently Windows has a length limit on file names and doesnt let you delete it if the file name and path is way too long. Although it doesn't prevent us from creating these files.

If I try to delete them from Explorer I get following error:
Cannot delete [file name]: The file name you specified is not valid or too long.  
Specify a different file name

I even tried to delete it from DOS but it dint help. I tried rmdir /S /Q <<folder name>> and also robocopy option to purge the folder and files but it did not help.

Some posts suggested to use a third party tools like 7zip etc, which din't seem a good idea.

As a final resort I wrote a small Java Program to fix this issue. Following is my program to delete the files and directories recursively for long file path problem:

Please note that will work in Java 8. You will have to make small modifications to make it work in lower versions.

package com.ingole.bot.demo.function;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class DeleteLongPath {

public static void main(String[] args) throws IOException {

try {
//paths.forEach(System.out::println);

DeleteLongPath deleteLongPath = new DeleteLongPath();
while(true) {

Stream<Path> paths = Files.walk(Paths.get("C:\\research\\vclone-parent\\"
+ "vclone-client\\src\\main\\java\\com\\vclone\\claims"));

paths.forEach(deleteLongPath::removeFile);
}

} catch (Exception e) {
//e.printStackTrace();
}

}

private void removeFile(Path path) {

try {
if(Files.deleteIfExists(path)){
System.out.println("Deleted path " + path.toString());
}
} catch (Exception e) {
//e.printStackTrace();
}
}

}

No comments:

Post a Comment