问题
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