不同系统的文件路径分隔符获取File.separator

程序中经常涉及到下载静态文件。但是运行在不同的系统上的文件路径和字符分隔符是不一样的。考虑到兼容性,所以需要获取自动获取系统的这些属性。File类的一些静态属性就可以满足。

File类有几个类似separator的静态字段,都是与系统相关的,在编程时应尽量使用。

public static final char separatorChar

与系统有关的默认名称分隔符。此字段被初始化为包含系统属性 file.separator 值的第一个字符。在 UNIX 系统上,此字段的值为 '/';在 Microsoft Windows 系统上,它为 '\'。

public static final String separator

与系统有关的默认名称分隔符,为了方便,它被表示为一个字符串。此字符串只包含一个字符,即 separatorChar。

public static final char pathSeparatorChar

与系统有关的路径分隔符。此字段被初始为包含系统属性 path.separator 值的第一个字符。此字符用于分隔以路径列表 形式给定的文件序列中的文件名。在 UNIX 系统上,此字段为 ':';在 Microsoft Windows 系统上,它为 ';'。

public static final String pathSeparator

与系统有关的路径分隔符,为了方便,它被表示为一个字符串。此字符串只包含一个字符,即 pathSeparatorChar。

当我们需要组装某个下载文件的路径时可以通过以下方式File.separator

 //resource下面的文件的路径
    public static final String PATH = File.separator + String.join(File.separator, "test", "path1");

/**
     * 下载文件
     *
     * @param dir   路径
     * @param fileName 原名称
     * @param response    返回
     * @throws IOException 异常
     */
    public static void download(String dir, String fileName, HttpServletResponse response) throws IOException {
        String path = StringUtils.isBlank(dir) ? (getPath(PATH) + File.separator) : (getPath(PATH) + File.separator + dir + File.separator);
        Path file = Paths.get(path, fileName);
        Files.copy(file, response.getOutputStream());
    }

 /**
     * 获取resource目录下suffix文件的完整路径
     *
     * @param suffix
     * @return
     */
    private static String getPath(String suffix) {
        try {
            return URLDecoder.decode(getClassPath() + suffix, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值