java - 从 URI 的 PATH 读取文件

标签 java io java-io

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

最佳答案

假设你有 URIString fileName 中,您可以轻松读取 url:

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

检查 this link了解更多信息

关于java - 从 URI 的 PATH 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30016832/

相关文章:

java - 理解java的各种I/O系统

java - 将 OutputStream 转换为字符串

Android:如何在内部存储器上存储数据?

java - 使具有相同删除二进制文件的通用返回类型兼容吗?

java - Appfuse - Spring 4 应用程序无法在 Tomcat 7 上部署

c - 在 C 中验证伪随机数据

java - 使用字符串变量时读取文件的差异

java - FileWriter写入文件

java - Tomcat-KeyCloak : FAIL -Deployed application at context path but context failed to start

java - 如何在 Hibernate Search 中正确使用 @ContainedIn 注解?