On Tuesday, Aug 26, 2003, at 15:56 Europe/London, Jason Dillon wrote:

String configFromSomewhere = ....
File file = new File(new URI(URLEncoder(configFromSomewhere));

Can you actually read a file using this?

The test code that I used allowed me to get the last modification date of the file, so the file clearly works in the right place. I did not test it using a FileInputStream or FileReader.


I modified the example code pasted last time to get

import java.net.*;
import java.io.*;
public class Test {
  public static void main(String args[]) throws Exception {
    String u = args[0];
    System.out.println("\"" + u + "\"");
    System.out.println(new URI(u));
    System.out.println(new File(new URI(u)));
    File file = new File(new URI(u));
    FileInputStream fin = new FileInputStream(file);
    byte buffer[] = new byte[1024];
    fin.read(buffer);
    System.out.println("Data:";);
    System.out.write(buffer);
    System.out.println("eData");

    }
    }

and it worked seamlessly at printing out the contents of the file with a %20 in the directory space.

(Note: this is tested/run on Mac OS X.2.6 using Java 1.4; it may be different on 'doze systems, but I wouldn't expect there to be a difference)

Note that as Daniel says, you may need to ensure that the protocol isn't also encoded as part of the URI, but there are constructors in the URI itself that allows for this:

http://java.sun.com/j2se/1.4.2/docs/api/java/net/URI.html

o The single-argument constructor requires any illegal characters in its argument to be quoted and preserves any escaped octets and other characters that are present.
o The multi-argument constructors quote illegal characters as required by the components in which they appear. The percent character ('%') is always quoted by these constructors. Any other characters are preserved.


If you are appending the 'file:///' on yourself (and the file is being read from somwhere else) then using a multi-part URI will solve this problem for you, encoding where necessary.

new URI("file",null,myFileName,null) // encodes right part automatically. First null is 'host' (may be empty for file URIs), second null is fragment (i.e. after #)

Regards,

Alex.



Reply via email to