Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

java - Is there a way to get the path of a File with "/" instead of ""?

I am making an HTTP Server in Java so that (on start) it finds all files in a directory (and it's sub-directories) and adds them to the server. But when getting the path of a file and trying to give it to HttpServer.createContext(), it throws a java.lang.IllegalArgumentException: Illegal value for path or protocol. (with the string argument, say "folder/index.html"). To get this value, I used

file.getParent().substring(24) + "/" + file.getName()

I used substring because I had to exclude the folder the web server is in. The illegal character is the backslash. I have tried extending File to change separator and separatorChar, but that only created 2 new variables. While using String.replace() didn't seem to have any effect. Is there a different method than File.getParent or File.getPath that I can use, or is there a way to use String.replace that I am not seeing?

EDIT: String.replace() seems to be the best answer... But I am not completely sure how to use it.

EDIT 2: For some reason the backslash isn't showing up, so I changed it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to use the java System.getProperty.

Notice that, in this context, "file.separator" is a key which we are using to get this property from current system executing the java VM.

Insteady of using a slash (/), you should choose a platform agnostic file separator, as an example it should be:

    String separator = System.getProperty("file.separator");
    System.out.println(separator);
    // unix / , windows 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...