使用URI复制时,不支持文件名中的特殊字符

时间:2013-03-26 16:52:19

标签: java copy uri special-characters illegal-characters

我需要使用URI将文件(文件名包含特殊字符)从一个路径复制到另一个路径。但它引发了一个错误。如果成功复制,如果文件名不包含特殊字符。你能告诉我如何使用URI从一个路径到另一个路径复制带有特殊字符的文件名。我已经复制了下面的代码和错误。

代码: -

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();
        }
  }
}

错误: -

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

感谢您对此进行调查......

2 个答案:

答案 0 :(得分:0)

文件名应为%-escaped。例如,实际文件名中的空格在URI中变为%20。如果您使用具有多个参数的构造函数之一,java.net.URI类可以为您执行此操作:

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

请参阅HTTP URL Address Encoding in Java

答案 1 :(得分:0)

您可以尝试使用java.net.uri