2013-03-26 50 views
0

複製我需要從一個路徑複製文件(文件名中包含特殊字符),使用URI另一條路徑。但它會拋出一個錯誤。如果它成功複製,如果文件名不包含特殊字符。你能否告訴我如何使用特定字符的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 

感謝您尋找到這...

+0

不確定,但你可以嘗試編碼的文件名! – 2013-03-26 16:53:02

回答

0

的文件名應該是%-escaped。例如,實際文件名中的空格變爲URI中的%20。

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

HTTP URL Address Encoding in Java:如果你使用一個構造函數與幾個參數的java.net.URI類可以爲你做到這一點。

+0

感謝它的工作。你能告訴我爲什麼下面的代碼不工作。 file = new File(new URI(file:///home/maria/input/3.-^%&.txt)) – user2040497 2013-03-26 18:09:44

+0

'^'和'%'是特殊字符,它們需要轉義。作爲'%5E'的'^'和'%25'的'%'。請參閱我引用的維基百科文章。 – 2013-03-26 20:29:49

相關問題