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
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With