Huy Tran Huy Tran - 1 year ago 76
Java Question

Java: handle special character in URI

I am trying to access a file from URI, unfortunately, that file path contain special name.

For example: file://C:/6-6+hf.1-181/db/mssql-ddl.sql

In detail, below is my code (scriptFile has above value):

File tempFile = FileUtility.fileFromUri(new URI(scriptFile));

Which fileFromUri function is

public static File fileFromUri(URI uri) {
try {
if(uri.getScheme() == null) {
uri = (new File(uri.getPath())).toURI();
} else if(!uri.getScheme().equals("file")) {
return null;

String fileName = uri.toURL().getFile();
return new File(URLDecoder.decode(fileName, "UTF8"));
} catch (Exception var2) {
return null;

I have exception like this C:/6-6+hf.1-181/db/mssql-ddl.sql
(The system cannot find the path specified) at Method) ~[?:1.8.0_65] at ~[?:1.8.0_65]
~[?:1.8.0_65] at
~[?:1.8.0_65] at
~[common-tool-develop-SNAPSHOT.jar:?] at
~[classes/:?] at
[classes/:?] at
[classes/:?] at
[common-tool-develop-SNAPSHOT.jar:?] at

I know that this exception is because I have used URLDecoder before, and after decode, Java translate '+' character to become space character. The solution may be just replace '+' character with others and then replace it later. However, I don't want to use that approach.

So can you help me with other solution for this?
Thanks a lot!

Answer Source

when you pass the path through URI, you should encode it first, if you use ajax, maybe encodeURIComponent() method is proper. like this:


if you use java URLEncode.encode(String str, String env) method is proper.

    String path = "file://C:/6-6+hf.1-181/db/mssql-ddl.sql";
    String path1 = URLEncoder.encode(path,"UTF-8");
    String path2 = URLDecoder.decode(path1,"UTF-8");


Hope this can Help you...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download