简体   繁体   English

从URI的PATH读取文件

[英]Reading file from PATH of URI

I have to read a file which can be local or in remote. 我必须读取一个本地或远程文件。
The file path or URI will come form user input. 文件路径或URI将来自用户输入。
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 参数String fileName是用户输入,可以是本地文件或URI的路径
How can i modify this method to work with both Local path and URI ? 我如何修改此方法以同时使用Local pathURI

Suposing you have the URI in String fileName you can read url easily with: 假设您在String fileName具有URI ,则可以使用以下命令轻松读取url:

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

Check this link for further info 检查此链接以获取更多信息

File class has also a constructor based on the URI so it easy to say new File(uri).. and everything stays the same. File类也具有基于URI的构造函数,因此可以很容易地说出新File(uri)..并且所有内容保持不变。 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". 但是,URI依赖于系统,如规范所述:“绝对分层的URI,其方案等于“文件”,非空路径组件以及未定义的权限,查询和片段组件”。

I think that if you need to read something remote, the best way to do it is by using Sockets. 我认为,如果您需要远程阅读某些内容,最好的方法是使用套接字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM