相对路径: String mdbDirPath = "./" + "taskPackage"; (当前工程目录同级)
拼路径: String path = mdbDirPath + "\\" + "1报送通知1.mdb";
获取文件流:InputStream inputStream = new FileInputStream(annexFile);
Java解压zip和rar格式到指定目录
@NotNull
private SolAttachUploadResponse getZipUploadResponse(String instId, String instContentParentId, MultipartFile file, InstBusinessInfo instBusinessInfo) {
File pathFile = null;
InputStream inputStream = null;
try {
SolAttachUploadResponse zipUploadResponse = new SolAttachUploadResponse();
if (file.isEmpty()) {
throw new IOException("要解压的文件内容为空");
}
String descDir = "./unzip";
pathFile = new File(descDir);
if (!pathFile.exists()) {
boolean mkdirResult = pathFile.mkdirs();
}
inputStream = file.getInputStream();
this.unzipWithStream(inputStream, descDir);
File fileZip = new File(descDir);
File[] files = fileZip.listFiles();
for (File file1 : files) {
zipUploadResponse = this.getZipUploadResponse(instId, instContentParentId, file1, instBusinessInfo);
}
return zipUploadResponse;
} catch (Exception e) {
throw new BusinessException(e.getMessage());
} finally {
try {
inputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
this.deleteDir(pathFile);
}
}
public void unzipWithStream(InputStream inputStream, String descDir) {
if (!descDir.endsWith(File.separator)) {
descDir = descDir + File.separator;
}
try (ZipInputStream zipInputStream = new ZipInputStream(inputStream, Charset.forName("GBK"))) {
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
String zipEntryNameStr = zipEntry.getName();
String zipEntryName = zipEntryNameStr;
if (zipEntryNameStr.contains("/")) {
String str1 = zipEntryNameStr.substring(0, zipEntryNameStr.indexOf("/"));
zipEntryName = zipEntryNameStr.substring(str1.length() + 1);
}
String outPath = (descDir + zipEntryName).replace("\\\\", "/");
File outFile = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if (!outFile.exists()) {
outFile.mkdirs();
}
if (new File(outPath).isDirectory()) {
continue;
}
writeFile(outPath, zipInputStream);
zipInputStream.closeEntry();
}
zipInputStream.closeEntry();
System.out.println("======解压成功=======");
} catch (IOException e) {
System.out.println("压缩包处理异常,异常信息{}" + e);
}
}
public static void writeFile(String filePath, ZipInputStream zipInputStream) {
try (OutputStream outputStream = Files.newOutputStream(Paths.get(filePath))) {
byte[] bytes = new byte[4096];
int len;
while ((len = zipInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
}
} catch (IOException ex) {
System.out.println("解压文件时,写出到文件出错");
}
}
public boolean deleteDir(File dir) {
if (dir.isDirectory()) {
File[] children = dir.listFiles();
if (children != null) {
for (File child : children) {
boolean success = deleteDir(child);
if (!success) {
return false;
}
}
}
}
return dir.delete();
}
Java压缩zip
@GetMapping("/downloadZip")
@ApiOperation(value = "下载压缩包")
@ApiImplicitParam(name = "instId", value = "实例id", required = true, paramType = "query", dataTypeClass = String.class)
public void downloadZip(@RequestParam("instId") String instId, HttpServletResponse response) {
Asserts.isEmpty(instId, "实例id[instId]不能为空");
InputStream inputStream = null;
OutputStream outputStream = null;
try {
businessContentService.zipAttachTree(instId,response);
outputStream.flush();
} catch (Exception e) {
response.setStatus(SC_BAD_REQUEST);
try {
if (outputStream != null) {
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Type", "application/json;charset=utf-8");
outputStream.write(JSON.toJSONString(R.fail(e.getMessage())).getBytes());
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
@Override
public void zipAttachTree(String instId, HttpServletResponse response) {
InstBusinessInfo instBusinessInfo = instBusinessInfoMapper.selectById(instId);
String instTitle = instBusinessInfo.getInstTitle();
if (instBusinessInfo == null) {
throw new BusinessException(instId);
}
BusinessContentRequest instanceContentRequest = new BusinessContentRequest();
BusinessContentResponse contentResponse = null;
instanceContentRequest.setInstId(instId);
instanceContentRequest.setGroupEnum(BusinessContentGroupEnum.DIR_TREE);
try {
contentResponse = this.getBusinessContent(instanceContentRequest);
} catch (Exception e) {
e.printStackTrace();
}
List<BusinessContentVO> contentVOList = contentResponse.getContentVOList();
File directory = new File("./" + instTitle);
directory.mkdir();
this.getFileName(contentVOList, new StringBuilder(), instTitle);
File file = new File("./" + instTitle);
File zipFile = null;
List<File> souceFileList = new ArrayList();
try {
souceFileList.add(file);
zipFile = new File(instTitle + ".zip");
ZipUtil.toZip(zipFile.getName(), souceFileList);
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(zipFile));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipFile.getName(), "UTF-8"));
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (file!=null && file.exists()){
FileUtil.del(file);
}
if (zipFile != null && zipFile.exists()) {
zipFile.delete();
}
}
}
public void getFileName(List<BusinessContentVO> contentVOList, StringBuilder sb, String instTitle) {
List<StringBuilder> fileNames = new ArrayList<>();
for (BusinessContentVO contentVO : contentVOList) {
OutputStream outputStream = null;
StringBuilder newSb = new StringBuilder(sb);
if (Func.isEmpty(contentVO.getDataId())) {
File directory = new File("./" + instTitle + "/" + contentVO.getNodeName());
directory.mkdir();
newSb.append(contentVO.getNodeName() + "/");
} else {
String dataId = contentVO.getDataId();
InstFileInfo instFileInfo = instFileInfoMapper.selectById(dataId);
InputStream inputStream = minioTemplate.getObject(instFileInfo.getFilePath());
String fileName = "./" + instTitle + "/" + sb + "/" + contentVO.getNodeName() + "";
File outputFile = new File(fileName);
try {
outputStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
List<BusinessContentVO> childrenList = contentVO.getChildren();
if (childrenList != null) {
getFileName(childrenList, newSb, instTitle);
}
}
}
将流写到文件中
MultipartFile file
InputStream is = file.getInputStream();
ZipInputStream zipInputStream = new ZipInputStream(is, Charset.forName("UTF-8"));
File jsonFile = new File("./pre/" + zipEntryNameStr);
this.writeFile(jsonFile.getAbsolutePath(), zipInputStream);
public void writeFile(String filePath, ZipInputStream zipInputStream) {
try (OutputStream outputStream = new FileOutputStream(filePath)) {
byte[] bytes = new byte[4096];
int len;
while ((len = zipInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
}
} catch (IOException ex) {
System.out.println("解压文件时,写出到文件出错");
}
}
解析导入的zip压缩包
@Override
public Object importTaskPackage(MultipartFile file) {
File zipFile = UnZipUtil.getFile(file);
String path = null;
if (StringUtils.isBlank(taskPackagePath)) {
throw new BusinessException("unzip.path.taskPackage 挂载目录路径未配置!");
}
String id = String.valueOf(IdUtil.getId());
String mdbDirPath = taskPackagePath + id;
File unzipFile = new File(mdbDirPath);
if (!unzipFile.exists()) {
unzipFile.mkdirs();
}
try {
UnZipUtil.unzipFile(zipFile.getPath(), mdbDirPath);
List<UnzipFileVo> unzipList = UnZipUtil.unzip(zipFile);
boolean format = false;
boolean formatTwo = false;
for (UnzipFileVo unzipFileVo : unzipList) {
if ("2附件".equals(unzipFileVo.getName())) {
format = true;
} else {
if ("1报送通知.mdb".equals(unzipFileVo.getName())) {
formatTwo = true;
}
}
}
if (!(format && formatTwo)) {
throw new BusinessException("上传的任务包格式有误,请检查任务包!");
}
String annexPath = mdbDirPath;
File folder = new File(annexPath);
File[] files = folder.listFiles();
List<FromFileUploadResponse> annexDatas = new ArrayList<>();
if (files != null) {
for (File annexFile : files) {
if (annexFile.isFile() && !"mdb".equals(FileUtil.getSuffix(annexFile.getName())) && !"json".equals(FileUtil.getSuffix(annexFile.getName()))) {
System.out.println(annexFile.getName());
String objectName = "taskPackage/" + cn.hutool.core.date.DateUtil.year(new Timestamp(System.currentTimeMillis())) + "/" + IdUtil.getId() + "."
+ FileUtil.getSuffix(annexFile.getName());
InputStream inputStream = new FileInputStream(annexFile);
String paths = fileService.putObject(objectName, inputStream);
inputStream.close();
InstFileInfo fileInfo = new InstFileInfo();
fileInfo.setFileName(annexFile.getName());
fileInfo.setFileSize(annexFile.length());
fileInfo.setExtension(FileUtil.getSuffix(annexFile.getName()));
fileInfo.setStatus(1);
fileInfo.setFilePath("bpm/" + objectName);
instFileInfoMapper.insert(fileInfo);
FromFileUploadResponse response = new FromFileUploadResponse();
response.setFileSize(file.getSize());
BeanUtils.copyProperties(fileInfo, response);
annexDatas.add(response);
String formatLink = fileService.formatLink(paths);
}
}
}
path = mdbDirPath + "\\" + "1报送通知.mdb";
this.insertRMBData(path, annexDatas);
} catch (IOException e) {
throw new BusinessException("解析任务包出错!");
} finally {
if (unzipFile != null && unzipFile.exists()) {
UnZipUtil.deleteFile(unzipFile);
}
zipFile.delete();
}
return null;
}
public void insertRMBData(String path, List<FromFileUploadResponse> annexDatas) {
Connection connection = AccessUtil.getAccessConnection(path, "", "");
try {
List<Map<String, Object>> rwbMapList = AccessUtil.select(connection, "XM_SJBSTZB");
for (Map<String, Object> map : rwbMapList) {
String jsonString = JSONObject.toJSONString(map);
JSONObject jsonObject = JSONObject.parseObject(jsonString);
SsRwb ssRwb = jsonObject.toJavaObject(SsRwb.class);
UUID uuid = UUID.randomUUID();
String uuidString = uuid.toString();
ssRwb.setId(uuidString);
ssRwb.setCjrXm(jsonObject.get("CJR").toString());
ssRwb.setCjSj(new Date());
if (annexDatas.size() > 0) {
Gson gson = new Gson();
String annexJson = gson.toJson(annexDatas);
ssRwb.setFj(annexJson);
}
ssRwbMapper.insert(ssRwb);
}
} catch (Exception e) {
throw new BusinessException("任务包解析数据插入任务表报错!");
} finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
下载文件响应
public void tableExport(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
OutputStream outputStream = null;
try {
String fileName = "数据表" + ".docx";
response.reset();
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ";filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));
outputStream = response.getOutputStream();
formService.tableExport(file, outputStream);
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
try {
if (outputStream != null) {
outputStream.write(JSON.toJSONString(R.fail(e.getMessage())).getBytes());
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
throw new RuntimeException();
}
}
}
if (fileDataMap.containsKey("toInputStream")) {
InputStream toInputStream = (InputStream)fileDataMap.get("toInputStream");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = toInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
批量下载文件压缩成zip格式
@GetMapping("/downloadZip")
@ApiOperation(value = "批量下载文件")
@ApiImplicitParam(name = "ids", value = "主键id,多个值英文,隔开", required = true, paramType = "query", dataTypeClass = String.class)
public void downloadZip(@RequestParam("ids") String ids, HttpServletResponse response) {
OutputStream outputStream = null;
try {
biMaterialService.zipAttach(ids,response);
outputStream.flush();
} catch (Exception e) {
response.setStatus(SC_BAD_REQUEST);
try {
if (outputStream != null) {
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Type", "application/json;charset=utf-8");
outputStream.write(JSON.toJSONString(R.fail(e.getMessage())).getBytes());
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
@Override
public void zipAttach(String ids, HttpServletResponse response) {
List<Long> idList = Func.toLongList(ids);
Integer type = this.getById(idList.get(0)).getType();
String name = MaterialTypeEnum.getName(type);
File tempDir = new File(System.getProperty("java.io.tmpdir"), "attachments");
if (!tempDir.exists()) {
tempDir.mkdirs();
}
try (ZipOutputStream zipOut = new ZipOutputStream(Files.newOutputStream(Paths.get(tempDir.getPath() + File.separator + "attachments.zip")))) {
for (Long id : idList) {
String objectName = this.getById(id).getStorePath();
if (objectName.contains("/minio/")) {
int startIndex = objectName.indexOf("/minio/") + "/minio/".length();
objectName = objectName.substring(startIndex);
}
InputStream inputStream = minIoUtil.getObject(objectName);
String tempFileName = objectName.substring(objectName.lastIndexOf("/") + 1);
File tempFile = new File(tempDir.getPath() + File.separator + tempFileName);
try (OutputStream outputStream = Files.newOutputStream(tempFile.toPath())) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
}
zipOut.putNextEntry(new ZipEntry(tempFileName));
try (FileInputStream fileInputStream = new FileInputStream(tempFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = fileInputStream.read(buffer)) > 0) {
zipOut.write(buffer, 0, length);
}
}
inputStream.close();
tempFile.delete();
}
} catch (IOException e) {
e.printStackTrace();
}
try (FileInputStream fileInputStream = new FileInputStream(tempDir.getPath() + File.separator + "attachments.zip")) {
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(name + ".zip", "UTF-8") + "\"");
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = fileInputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
this.deleteDir(tempDir);
}
private void deleteDir(File dir) {
if (dir.isDirectory()) {
File[] children = dir.listFiles();
if (children != null) {
for (File child : children) {
deleteDir(child);
}
}
}
dir.delete();
}
文件访问路径
sourceCode:
sourceCodeUrl: /data/project/template Linux
sourceCodeUrl2: D:\GDIdeaWorkBi\template windows
根据服务的文件,压缩导出源代码
@PostMapping("/downloadCode")
@ApiOperation(value = "导出源代码")
@ApiOperationSupport(order = 19)
@ApiImplicitParams({
@ApiImplicitParam(name = "files", value = "需要上传的文件流对象", paramType = "query", dataType = "MultipartFile", required = true),
@ApiImplicitParam(name = "pagePath", value = "页面文件储存路径", paramType = "query", dataType = "String", required = true),
@ApiImplicitParam(name = "routePath", value = "路由文件储存路径", paramType = "query", dataType = "String", required = true),
@ApiImplicitParam(name = "fileIds", value = "文件ID,多个值英文,隔开", paramType = "query", dataType = "String", required = true),
})
public void downloadCode(MultipartFile[] files, String pagePath, String routePath, String fileIds,HttpServletResponse response){
OutputStream outputStream = null;
try {
iProjectService.downloadCode(files,pagePath,routePath,fileIds,response);
outputStream.flush();
} catch (Exception e) {
response.setStatus(SC_BAD_REQUEST);
try {
if (outputStream != null) {
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Type", "application/json;charset=utf-8");
outputStream.write(JSON.toJSONString(R.fail(e.getMessage())).getBytes());
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
void downloadCode(MultipartFile[] files,String pagePath,String routePath, String fileIds, HttpServletResponse response);
@Value("${sourceCode.sourceCodeUrl}")
private String sourceCodeUrl;
@Value("${sourceCode.fileIdUrl}")
private String filePath;
@Override
public void downloadCode(MultipartFile[] files, String pagePath, String routePath, String fileIds, HttpServletResponse response) {
File oFile = new File(sourceCodeUrl);
File routDirectory = new File(routePath);
if (!routDirectory.exists()) {
routDirectory.mkdirs();
}
File pageDirectory = new File(pagePath);
if (!pageDirectory.exists()) {
pageDirectory.mkdirs();
}
File fileDirectory = new File(filePath);
if (!fileDirectory.exists()) {
fileDirectory.mkdirs();
}
try {
for (MultipartFile file : files) {
String nameSuffix = cn.hutool.core.io.FileUtil.getSuffix(file.getOriginalFilename());
if ("vue".equals(nameSuffix)) {
File destFile = new File(pagePath + File.separator + file.getOriginalFilename());
try (InputStream inputStream = file.getInputStream();
OutputStream outputStream = Files.newOutputStream(destFile.toPath())) {
IOUtils.copy(inputStream, outputStream);
}
} else {
File destFile = new File(routePath + File.separator + file.getOriginalFilename());
try (InputStream inputStream = file.getInputStream();
OutputStream outputStream = Files.newOutputStream(destFile.toPath())) {
IOUtils.copy(inputStream, outputStream);
}
}
}
this.handleTemplateFile(fileIds, filePath);
File zipFile = new File("template.zip");
try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile))) {
zipFolder(oFile, oFile, zipOut);
}
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=\"template.zip\"");
try (InputStream zipStream = Files.newInputStream(zipFile.toPath());
OutputStream outputStream = response.getOutputStream()) {
IOUtils.copy(zipStream, outputStream);
}
clearDirectory(routDirectory);
clearDirectory(pageDirectory);
clearDirectory(fileDirectory);
} catch (Exception e) {
throw new BusinessException("压缩源码报错!" + e.getMessage());
}
}
private void handleTemplateFile(String fileIds, String filePath) throws IOException {
InputStream inputStream = null;
try {
if (StringUtil.isNotEmpty(fileIds)) {
List<String> ids = new ArrayList<>(Arrays.asList(fileIds.split(",")));
for (String fileId : ids) {
SysFile sysFile = sysFileMapper.selectById(fileId);
if (Objects.nonNull(sysFile)) {
String objectName = sysFile.getFileUrl();
String fileName = fileId + "." + sysFile.getFileSuffix();
if (objectName.contains("/minio/")) {
int startIndex = objectName.indexOf("/minio/") + "/minio/".length();
objectName = objectName.substring(startIndex);
}
inputStream = minIoUtil.getObject(objectName);
File destFile = new File(filePath + File.separator + fileName);
try (OutputStream outputStream = Files.newOutputStream(destFile.toPath())) {
IOUtils.copy(inputStream, outputStream);
}
}
}
}
} catch (Exception e) {
throw new BusinessException("导出源码处理静态文件报错!" + e.getMessage());
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
private void zipFolder(File directory, File baseDir, ZipOutputStream zipOut) throws IOException {
File[] files = directory.listFiles();
for (File file : files) {
if (file.isDirectory()) {
String relativePath = baseDir.toPath().relativize(file.toPath()).toString() + "/";
ZipEntry zipEntry = new ZipEntry(relativePath);
zipOut.putNextEntry(zipEntry);
zipFolder(file, baseDir, zipOut);
} else {
String relativePath = baseDir.toPath().relativize(file.toPath()).toString();
try (FileInputStream fis = new FileInputStream(file)) {
ZipEntry zipEntry = new ZipEntry(relativePath);
zipOut.putNextEntry(zipEntry);
IOUtils.copy(fis, zipOut);
}
}
}
}
private void clearDirectory(File directory) {
for (File file : directory.listFiles()) {
if (file.isDirectory()) {
clearDirectory(file);
}
file.delete();
}
}
sourceCode:
sourceCodeUrl: /data/project/template
sourceCodeUrl2: D:\GDIdeaWorkBi\template
fileIdUrl: /data/project/template/src/views/exportDemo/assets/