tags:

views:

70

answers:

3

In Java can I create a URI for a file located locally in the hard drive? If so, how should it be constructed?

+1  A: 

Try below:

URI uri = new URI("file:///C:/other/mydir/myfile.txt");
Taylor Leese
I have used the following code String uri = "file:///C:/Documents and Settings/Ant/Desktop/travel.owl";but it gives me error:SEVERE: Exception caught -- java.net.URISyntaxException: Illegal character in path at index 20: file:///C:/Documents and Settings/Ant/Desktop/travel.owlAny idea?
Tony
@Anto: I think it should be encoded url (i.e. without whitespaces)
Roman
do I have to replace white spaces with some symbol or do I have to just cut the white spaces?
Tony
@Anto: try URLEncoder http://java.sun.com/j2se/1.5.0/docs/api/java/net/URLEncoder.html
Roman
+2  A: 

Look at File documentation:

File has a constructor, which takes URI as a param, and it also has method toUri () if you want to get URI from existing file. You can play with that to understand how the things should be done.

You can also read about URI (it's not a java term). There is an example in wikipedia:

file:///home/username/RomeoAndJuliet.pdf

Roman
+2  A: 

URI uri = new URI("file:///filename.txt");

If you're using Windows:

URI uri = new URI("file:///C:/fun/filename.txt");

ebiester