在文件上传对于拼接时,加入了+File.separator+的作用

其实 File.separator 的作用相当于 ' \  '

在 windows 中 文件文件分隔符 用 ' \ ' 或者 ' / ' 都可以

但是在 Linux 中,是不识别 ' \ '  的,而 File.separator 是系统默认的文件分隔符号,在 UNIX 系统上,此字段的值为 ' / '

在 Microsoft Windows 系统上,它为 ' \ ' 屏蔽了这些系统的区别。

所以用 File.separator 保证了在任何系统下不会出错。

此外 File 类还有:

1、separatorChar

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

2、pathSeparatorChar   

          与系统有关的路径分隔符,为了方便,它被表示为一个字符串

3、pathSeparator

          此字符用于分隔以路径列表形式给定的文件序列中的文件名

          在 UNIX 系统上此字段为 ' : '

          在 Microsoft Windows 系统上,它为 ' ; '

 

在项目中运用的实例:

String fileName = file.getOriginalFilename();
// 判断文件类型是否符合要求
boolean b = ValidateFileUtil.validateFile(fileName);
if (!b){
throw new ZException(ErrorCode.BIZ_FILE_TYPE_ERROR.getMessage(),ErrorCode.BIZ_FILE_TYPE_ERROR);
}
// 上传之前根据文件名判断是否重复上传
if (uploadRecordDao.clueFileExists(fileName) > 0){
throw new ZException(ErrorCode.BIZ_FILE_SAME.getMessage(),ErrorCode.BIZ_FILE_SAME);
}
// 文件服务器路径按天划分
Date datePath = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = sdf.format(datePath);
String destFile = filePath + File.separator + dateStr + File.separator + fileName;
String tmpPath = filePath + File.separator + dateStr + File.separator + "tmp";
logger.info("destFile:{}",destFile);
File dest = new File(destFile);
if (!dest.getParentFile().exists()){
dest.getParentFile().mkdirs();
}

 

posted @ 2021-01-06 11:32  六月的雨莹  阅读(213)  评论(0编辑  收藏  举报