我必须读取本地或远程的文件。
文件路径或 URI
将来自用户输入。
目前我只读取本地文件,这样
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;
}
参数String fileName
是用户输入,可以是本地文件的路径或URI
我如何修改此方法以同时使用 Local path
和 URI
?
最佳答案
假设你有 URI在 String fileName
中,您可以轻松读取 url:
URI uri = new URI(filename);
File f = new File(uri);
检查 this link了解更多信息
关于java - 从 URI 的 PATH 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30016832/