Huy Tran Huy Tran - 1 month ago 17
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


java.io.FileNotFoundException: C:/6-6+hf.1-181/db/mssql-ddl.sql
(The system cannot find the path specified) at
java.io.FileInputStream.open0(Native Method) ~[?:1.8.0_65] at
java.io.FileInputStream.open(FileInputStream.java:195) ~[?:1.8.0_65]
at java.io.FileInputStream.(FileInputStream.java:138)
~[?:1.8.0_65] at java.io.FileReader.(FileReader.java:72)
~[?:1.8.0_65] at
com.automic.actions.common.utils.FileUtility.readFileAsString(FileUtility.java:70)
~[common-tool-develop-SNAPSHOT.jar:?] at
com.automic.actions.database.utils.SQLRunner.readStatementsFromFile(SQLRunner.java:117)
~[classes/:?] at
com.automic.actions.database.utils.SQLRunner.executeScript(SQLRunner.java:91)
[classes/:?] at
com.automic.actions.database.SQLFeature.run(SQLFeature.java:302)
[classes/:?] at
com.automic.actions.common.FeatureRunner.run(FeatureRunner.java:24)
[common-tool-develop-SNAPSHOT.jar:?] at
com.automic.actions.runner.DatabaseToolFileCmd.main(DatabaseToolFileCmd.java:25)
[classes/:?]


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

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

encodeURIComponent("file://C:/6-6+hf.1-181/db/mssql-ddl.sql")
//output
"file%3A%2F%2FC%3A%2F6-6%2Bhf.1-181%2Fdb%2Fmssql-ddl.sql"

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");
    System.out.println(path1);
    String path2 = URLDecoder.decode(path1,"UTF-8");
    System.out.println(path2);

    //output
    file%3A%2F%2FC%3A%2F6-6%2Bhf.1-181%2Fdb%2Fmssql-ddl.sql
    file://C:/6-6+hf.1-181/db/mssql-ddl.sql

Hope this can Help you...

Comments