java 从 URI 的 PATH 读取文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30016832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading file from PATH of URI
提问by Saif
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
我必须读取一个可以是本地或远程的文件。
文件路径或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;
}
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
?
参数String fileName
是用户输入,它可以是本地文件的路径或URI
如何修改此方法以同时使用Local path
和URI
?
采纳答案by Jordi Castilla
回答by iullianr
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".
File 类还有一个基于 URI 的构造函数,所以很容易说 new File(uri).. 并且一切都保持不变。然而,URI 是依赖于系统的,正如规范所说的“一个绝对的、分层的 URI,其方案等于“文件”,一个非空路径组件,以及未定义的权限、查询和片段组件”。
I think that if you need to read something remote, the best way to do it is by using Sockets.
我认为如果您需要远程读取某些内容,最好的方法是使用 Sockets。