程序中经常涉及到下载静态文件。但是运行在不同的系统上的文件路径和字符分隔符是不一样的。考虑到兼容性,所以需要获取自动获取系统的这些属性。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);
}
}