【问题标题】:Reading file from PATH of URI从 URI 的 PATH 读取文件
【发布时间】:2015-07-13 01:17:31
【问题描述】:

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

【问题讨论】:

标签: java io java-io


【解决方案1】:

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

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

查看this link了解更多信息

【讨论】:

  • 如果我弄错了,请原谅我,但我在String 类中看不到任何toURI() 方法
  • 对不起,我忘记了字符串到uri的转换xDDDD
  • 谢谢。我从您的回答中找到了一个很好的提示,但确切的提示。请编辑你的答案,我认为还有一些事情要说清楚,比如URI 对象上的url.toURI()(我猜是错字),我不需要考虑URL
【解决方案2】:

File 类也有一个基于 URI 的构造函数,所以很容易说 new File(uri).. 并且一切都保持不变。 但是,URI 是系统相关的,正如规范中所说的“一个绝对的、分层的 URI,其方案等于“文件”、非空路径组件以及未定义的权限、查询和片段组件。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    相关资源
    最近更新 更多