Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading file from PATH of URI

Tags:

java

io

java-io

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 ?

like image 228
Saif Avatar asked May 03 '15 17:05

Saif


1 Answers

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

like image 64
Jordi Castilla Avatar answered Oct 10 '22 17:10

Jordi Castilla