Reading file from PATH of URI
Asked Answered
M

2

9

I have to read a file which can be local or in remote.
The file path or URI will come form user input.
Currently I am reading only local file,this way

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 the user input which can be a path to local file or a URI
How can i modify this method to work with both Local path and URI ?

Mossberg answered 3/5, 2015 at 17:10 Comment(1)
You may have a look at this link - #1316860Electrocardiograph
T
6

Suposing you have the URI in String fileName you can read url easily with:

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

Check this link for further info

Tempest answered 3/5, 2015 at 17:13 Comment(3)
pardon me if i am mistaken,But i don't see any toURI() method in String classMossberg
sorry, i forgot string to uri conversion xDDDDTempest
thanks. I found a good hint from your answer but to the exact one. please edit you answer, i think there are still some thing to make it clear, like url.toURI() on a URI object (i guess a typo) and i don't need to consider URLMossberg
A
0

File class has also a constructor based on the URI so it easy to say new File(uri).. and everything stays the same. However, the URI is system-dependent, as specification says "An absolute, hierarchical URI with a scheme equal to "file", a non-empty path component, and undefined authority, query, and fragment components".

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

Abohm answered 3/5, 2015 at 17:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.