从 URI 的 PATH 读取文件

Reading file from PATH of URI

我必须读取本地或远程的文件。
文件路径或 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 pathURI

假设您在 String fileName 中有 URI,您可以通过以下方式轻松阅读 url:

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

检查 this link 了解更多信息

File class 也有一个基于 URI 的构造函数,所以很容易说出 new File(uri).. 一切都保持不变。 但是,URI 是系统相关的,如规范所述 "An absolute, hierarchical URI with a scheme equal to "file",一个非空路径组件,以及未定义的权限、查询和片段组件"。

我认为如果您需要远程读取某些内容,最好的方法是使用套接字。