Search code examples
javanio

java nio NoFilepatternException how to deal with spaces in file path


i have a file located at C:\Users\abc xyz\Downloads\designspec.docx i want to copy this file in another directory using this code

String sourceFilePathStr="‪C:\\Users\\abc xyz\\Downloads";
URI sourceFilePath = new URI(("file:///"+ sourceFilePathStr.replaceAll(" ", "%20")));

File source = new File(sourceFilePath.toString(),"designspec.docx");
File dest = new File("path to another directory","designspec.docx");
        try {
            inputChannel = new FileInputStream(source).getChannel();
            outputChannel = new FileOutputStream(dest).getChannel();
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
            log.info("copy complete");
        } finally {
            inputChannel.close();
            outputChannel.close();
        }

the above code is throwing exception

SEVERE: got NoFilepatternException {}
java.net.URISyntaxException: Illegal character in path at index 11: file:///‪C:\Users\abc%20xyz\Downloads
    at java.net.URI$Parser.fail(URI.java:2848)
    at java.net.URI$Parser.checkChars(URI.java:3021)
    at java.net.URI$Parser.parseHierarchical(URI.java:3105)
    at java.net.URI$Parser.parse(URI.java:3053)
    at java.net.URI.<init>(URI.java:588)

How can i resolve this exception please guide


Solution

  • What are you trying to do ?
    You shouldn't need to make manual replace of whitespace by %20.

    File.toURI() serves this goal.

    Besides, you issue is there I assume :

    File source = new File(sourceFilePath.toString(),"designspec.docx");
    

    You pass a String representation of the URI but that will not work with a File constructor that expects two pathname Strings.

    To resolve the docs from the folder, the URI is useless :

    String sourceFilePathStr="‪C:\\Users\\abc xyz\\Downloads";
    File source = new File(sourceFilePathStr,"designspec.docx");
    

    By the way, you could also use Path rather than File that is a better designed API :

    Path parentPath = Paths.get("‪C:\\Users\\abc xyz\\Downloads");
    Path filePath = Paths.get(parentPath, "designspec.docx");