Reading file from PATH URI

I need to read a file that can be local or remote.
The path to the file or URI

will be generated for user input.
I am currently only reading the local file, thus

public String readFile(String fileName)
{

    File file=new File(fileName);
    BufferedReader bufferedReader = null;
    try {
        bufferedReader = new BufferedReader(new FileReader(file));
        StringBuilder stringBuilder = new StringBuilder();
        String line;

        while ( (line=bufferedReader.readLine())!=null ) {
            stringBuilder.append(line);
            stringBuilder.append(System.lineSeparator());
        }
        return stringBuilder.toString();
    } catch (FileNotFoundException e) {
        System.err.println("File : \""+file.getAbsolutePath()+"\" Not found");
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        try {
            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

      

The parameter String fileName

is user input, which can be the path to a local file or URI


How can I change this method to work with Local path

and URI

?

+3


source to share


2 answers


Let's say you have a URI in String fileName

you can read the url easily:

URI uri = new URI(filename);
File f = new File(uri);

      



Check this link for more information

+5


source


The file class also has a URI based constructor, so it's easy to say a new file (uri) .. and everything stays the same. However, the URI is system dependent because the specification states "An absolute hierarchical URI with a schema equal to" file ", a non-empty path component, and undefined permissions, requests and fragments."



I think that if you need to read something remote, the best way to do it is to use Sockets.

0


source







All Articles