Special character in filename are not supported while copying using URI

有些话、适合烂在心里 提交于 2019-12-11 19:12:04

问题


I need to copy the files(file name contains special character) from one path to another path using URI. But its throws an error. If its successfully copied, if the filename not contains special character. Could you please advise me how to copy the file name with special character using URI from one path to another path. I have copied the code and error below.

Code:-

import java.io.*;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

public class test {
    private static File file = null;
    public static void main(String[] args) throws InterruptedException, Exception {
        String from = "file:///home/guest/input/3.-^%&.txt";
        String to = "file:///home/guest/output/3.-^%&.txt";
        InputStream in = null;
        OutputStream out = null;
        final ReadableByteChannel inputChannel;
        final WritableByteChannel outputChannel;
        if (from.startsWith("file://")) {
            file = new File(new URI(from));
            in = new FileInputStream(file);
        }

        if (from.startsWith("file://")) {
            file = new File(new URI(to));
            out = new FileOutputStream(file);
        }

        inputChannel = Channels.newChannel(in);
        outputChannel = Channels.newChannel(out);

        test.copy(inputChannel, outputChannel);
        inputChannel.close();
        outputChannel.close();
    }

    public static void copy(ReadableByteChannel in, WritableByteChannel out) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocateDirect(32 * 1024);
        while (in.read(buffer) != -1 || buffer.position() > 0) {
        buffer.flip();
        out.write(buffer);
        buffer.compact();
        }
  }
}

Error:--

Exception in thread "main" java.net.URISyntaxException: Illegal character in path at index 30: file:///home/maria/input/3.-^%&.txt
    at java.net.URI$Parser.fail(URI.java:2829)
    at java.net.URI$Parser.checkChars(URI.java:3002)
    at java.net.URI$Parser.parseHierarchical(URI.java:3086)
    at java.net.URI$Parser.parse(URI.java:3034)
    at java.net.URI.<init>(URI.java:595)
    at com.tnq.fms.test3.main(test3.java:29)
Java Result: 1

Thanks for looking into this...


回答1:


You can try to use the java.net.uri.




回答2:


The filenames should be %-escaped. For example, a space in the actual filename becomes a %20 in the URI. The java.net.URI class can do it for you if you use one of the constructors with several arguments:

new URI("file", null, "/home/guest/input/3.-^%&.txt", null);

See HTTP URL Address Encoding in Java.



来源:https://stackoverflow.com/questions/15642862/special-character-in-filename-are-not-supported-while-copying-using-uri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!