zoukankan      html  css  js  c++  java
  • Java根据路径获取文件内容


    给出一个资源路径、然后获取资源文件信息,常见三种方式:①网络地址 ②本地绝对路径 ③本地相对路径

    一、思路

    首先,给出一个string表示资源文件的标识,如何判断是网络中的文件还是本地的文件?

    *http开头的可以看成是网络文件
    *其余的可看成本地文件
    

    对于mac和linux系统而言:
    *以 / 和 ~ 开头的表示绝对路径
    *其他的看做是相对路径

    对于windows系统而言,绝对路径形如c: est.text
    *路径中包含 : 看成是绝对路径
    *以 开头看做的绝对路径

    二、实现

    判断操作系统:

    /**
     * 是否windows系统
     */
    public static boolean isWinOS() {
        boolean isWinOS = false;
        try {
            String osName = System.getProperty("os.name").toLowerCase();
            String sharpOsName = osName.replaceAll("windows", "{windows}").replaceAll("^win([^a-z])", "{windows}$1")
                    .replaceAll("([^a-z])win([^a-z])", "$1{windows}$2");
            isWinOS = sharpOsName.contains("{windows}");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isWinOS;
    }
    

    绝对路径与否判断:

    public static boolean isAbsFile(String fileName) {
        if (OSUtil.isWinOS()) {
            // windows 操作系统时,绝对地址形如  c:descktop
            return fileName.contains(":") || fileName.startsWith("\");
        } else {
            // mac or linux
            return fileName.startsWith("/");
        }
    }
    
    /**
     * 将用户目录下地址~/xxx 转换为绝对地址
     *
     * @param path
     * @return
     */
    public static String parseHomeDir2AbsDir(String path) {
        String homeDir = System.getProperties().getProperty("user.home");
        return StringUtils.replace(path, "~", homeDir);
    }
    

    文件获取封装类:

    public static InputStream getStreamByFileName(String fileName) throws IOException {
        if (fileName == null) {
            throw new IllegalArgumentException("fileName should not be null!");
        }
    
        if (fileName.startsWith("http")) {
            // 网络地址
            return HttpUtil.downFile(fileName);
        } else if (BasicFileUtil.isAbsFile(fileName)) {
            // 绝对路径
            Path path = Paths.get(fileName);
            return Files.newInputStream(path);
        } else if (fileName.startsWith("~")) {
            // 用户目录下的绝对路径文件
            fileName = BasicFileUtil.parseHomeDir2AbsDir(fileName);
            return Files.newInputStream(Paths.get(fileName));
        } else { // 相对路径
            return FileReadUtil.class.getClassLoader().getResourceAsStream(fileName);
        }
    }
    

    原文地址:
    灰灰blog

  • 相关阅读:
    unexpected inconsistency;run fsck manually esxi断电后虚拟机启动故障
    centos 安装mysql 5.7
    centos 7 卸载mysql
    centos7 在线安装mysql5.6,客户端远程连接mysql
    ubuntu 14.04配置ip和dns
    centos7 上搭建mqtt服务
    windows eclipse IDE打开当前类所在文件路径
    git 在非空文件夹clone新项目
    eclipse中java build path下 allow output folders for source folders 无法勾选,该如何解决 eclipse中java build path下 allow output folders for source folders 无法勾选,
    Eclipse Kepler中配置JadClipse
  • 原文地址:https://www.cnblogs.com/aixing/p/13327504.html
Copyright © 2011-2022 走看看