antonpuz
antonpuz

Reputation: 3316

What does file:// prefix mean when reading a file

I see two types of references to files, example: I have a file called a.txt located at: /tmp/a.txt

The two reference types are either pointing to it directly: "/tmp/a.txt", or adding a "hdfs,local,file" prefix to the file. I am wondering what is the meaning of using this prefix. The case of hdfs is trivial but what is the meaning of using the others? example:

    String file = "/tmp/a.txt";
    FileInputStream fileInputStream = new FileInputStream(file);
    System.out.println(fileInputStream.available());

    file = "local://tmp/a.txt";
    fileInputStream = new FileInputStream(file);
    System.out.println(fileInputStream.available());

    file = "file://tmp/a.txt";
    fileInputStream = new FileInputStream(file);
    System.out.println(fileInputStream.available());

The absolute path returned a result, the local and file paths threw FileNotFoundException

Upvotes: 2

Views: 6367

Answers (3)

Michal
Michal

Reputation: 2423

The File constructor does not support prefixes for the pathname parameter. That is the reason why the usage of prefixed pathname results in FileNotFoundException.

The JDK classes URL and URI supports the usage of prefixes such as in file://ftp.yoyodyne.com/pub/files/foobar.txt or in http://java.sun.com/j2se/1.3/.

Further, Spring supports prefixes such as file:/ or classpath:/ in its resource abstraction.

It is noteworthy that the File on one hand, and the different resource abstractions (the Spring one, the URL and URI) on the other one, that they represents quite different concepts.

Upvotes: 0

Ruslan
Ruslan

Reputation: 6290

file:// is protocol that refers to files on local network. Unlike http:// that refers to the resources via http request.

See more File URI Scheme
More File URI Slashes issue

You can use file prefix, but you need to convert it to a legal path:

String path = "file:///tmp/a.txt";
URI uri = new URI(path);
FileInputStream stream = new FileInputStream(new File(uri));

Upvotes: 3

Major
Major

Reputation: 562

As mentioned, the prefix file:// is part of a URI scheme, often used in webbrowsers. What it does is state that the object should be treated as a file. The file can be a local or remote file. Not every File handling api recognizes these prefixes.

Upvotes: 1

Related Questions