The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.io  [35 examples] > Filenames and Pathnames  [6 examples]

e14. Converting Between a Filename Path and a URL

    // Create a file object
    File file = new File("filename");
    
    // Convert the file object to a URL
    URL url = null;
    try {
        // The file need not exist. It is made into an absolute path
        // by prefixing the current working directory
        url = file.toURL();          // file:/d:/almanac1.4/java.io/filename
    } catch (MalformedURLException e) {
    }
    
    // Convert the URL to a file object
    file = new File(url.getFile());  // d:/almanac1.4/java.io/filename
    
    // Read the file contents using the URL
    try {
        // Open an input stream
        InputStream is = url.openStream();
    
        // Read from is
    
        is.close();
    } catch (IOException e) {
        // Could not open the file
    }

 Related Examples
e13. Constructing a Filename Path
e15. Getting an Absolute Filename Path from a Relative Filename Path
e16. Determining If Two Filename Paths Refer to the Same File
e17. Getting the Parents of a Filename Path
e18. Determining If a Filename Path Is a File or a Directory

See also: Directories    Encodings    Files    Parsing    Reading and Writing    Serialization   


© 2002 Addison-Wesley.