getFilePath ZipOutputStream

本文探讨了使用Java标准库中的ZipOutputStream进行文件压缩时出现的字符集乱码问题,并对比了Apache工具包中ZipOutputStream的表现。通过实例演示了如何正确设置字符集以避免乱码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

	/**
	 * 获取当前form文件或者文件夹绝对路径
	 * 
	 * @author ZengWenFeng
	 * @date 2017-09-06
	 * @param form 当前节点
	 * @param list 树结构所有节点列表(集合)
	 * @param path 默认输入为空字符串
	 * @return 返回当前节点对应文件或者文件夹目录字符串(文件为:曾文峰-目录/kkk/zwf13.xls  目录为:曾文峰-目录/kkk
	 */
	public String getFilePath(FbForm form, List<FbForm> list, String path)
	{
		if (form == null)
		{
			return "";
		}

		String id = form.getId();//id
		String fName = form.getName();//excel文件名
		String tName = form.getTablename();//数据库表名
		String pId = form.getPid();//父节点id

		// 父节点为空,则为一级目录或者一级文件
		if (pId == null || pId.trim().equals(""))
		{
			// 数据库表名为空,则是目录,返回目录名:曾文峰-目录
			if (tName == null || tName.trim().equals(""))
			{
				if (path.equals(""))
				{
					return fName;
				}
				else
				{
					return path;
				}
			}
			//数据库表名不为空,则是文件,直接返回excel文件名:曾文锋测试5.XLS
			else
			{
				if (path.equals(""))
				{
					return fName + ".xls";
				}
				else
				{
					return path;
				}
			}
		}
		// 父节点不为空
		else
		{
			FbForm parentForm = null;
			String id_parentForm = "";//id
			String fName_parentForm = "";//excel文件名
			String tName_parentForm = "";//数据库表名
			String pId_parentForm = "";//父节点id

			// 寻找父节点
			FbForm tempForm = null;
			for (int i = 0; i < list.size(); i++)
			{
				tempForm = list.get(i);

				if (tempForm == null)
				{
					continue;
				}

				// 如果找到父节点了
				if (pId.equals(tempForm.getId()))
				{
					parentForm = tempForm;
				}
			}

			if (parentForm == null)
			{
				return path;
			}

			id_parentForm = parentForm.getId();//id
			fName_parentForm = parentForm.getName();//excel文件名
			tName_parentForm = parentForm.getTablename();//数据库表名
			pId_parentForm = parentForm.getPid();//父节点id

			if (tName == null || tName.trim().equals(""))
			{
				if (path.equals(""))
				{
					path = fName_parentForm + "/" + fName;
				}
				else
				{
					path = fName_parentForm + "/" + path;
				}
			}
			else
			{
				if (path.equals(""))
				{
					path = fName_parentForm + "/" + fName + ".xls";
				}
				else
				{
					path = fName_parentForm + "/" + path;
				}
			}

			return getFilePath(parentForm, list, path);
		}
	}



我X,  ZipOutputStream  字符集乱码??明天整。




package zip;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import zip7rar.CompressFile;

/**
 * 
 *
 * @author ZengWenFeng
 */
public class ZipCompress
{
	/**
	 * java.util.zip.ZipOutputStream
	 * 
	 * 乱码
	 * 
	 * @throws IOException
	 */
	public static void test01() throws IOException
	{

		String[] fileNames = 
		{
			"E:/PRJ_J2EE/PrjFlexJava/java_src/zip/config.properties", 
			"E:/PRJ_J2EE/PrjFlexJava/java_src/zip/中文.properties", 
			"E:/PRJ_J2EE/PrjFlexJava/java_src/zip/中文.csv"
		};
		
		FileOutputStream f = new FileOutputStream("C:/Users/Administrator/Desktop/test.zip");

		CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());

		ZipOutputStream zos = new ZipOutputStream(csum);

		BufferedOutputStream out = new BufferedOutputStream(zos);

		zos.setComment("comment");
		for (String fileName : fileNames)
		{
			BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8"));
			zos.putNextEntry(new ZipEntry(fileName));

			String temp;
			while ((temp = in.readLine()) != null)
			{
				out.write(temp.getBytes("UTF-8"));
			}
			
			in.close();
			out.flush();
		}
		
		out.close();
	
	}
	
	/**
	 * org.apache.tools.zip.ZipOutputStream
	 * 没有乱码
	 * 
	 * @throws IOException
	 */
	public static void test02() throws IOException
	{

		File[] fileNames = 
		{
			new File("E:/PRJ_J2EE/PrjFlexJava/java_src/zip/config.properties"), 
			new File("E:/PRJ_J2EE/PrjFlexJava/java_src/zip/中文.properties"),
					new File("E:/PRJ_J2EE/PrjFlexJava/java_src/zip/中文.csv")
		};
		
		File zipfile = new File("C:/Users/Administrator/Desktop/test.zip");
		
		
		CompressFile.zipFiles(fileNames, zipfile);
	
	}
	
	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException
	{
		test02();
	}
}


package org.example.bim_design_service.controller; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.example.bim_design_service.dto.*; import org.example.bim_design_service.service.VersionControlService; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.util.List; // VersionController.java @RestController @RequestMapping("/api/version") @RequiredArgsConstructor public class VersionController { private final VersionControlService versionControlService; /** * 检查版本更新 */ @PostMapping("/check") public ResponseEntity<VersionCheckResponse> checkVersion( @Valid @RequestBody VersionCheckRequest request) { System.out.println(); VersionCheckResponse response = versionControlService.checkVersion(request); return ResponseEntity.ok(response); } /** * 检查模块更新 */ @PostMapping("/check-modules") public ResponseEntity<ModuleUpdateListResponse> checkModuleUpdates( @Valid @RequestBody ModuleUpdateCheckRequest request) { ModuleUpdateListResponse response = versionControlService.checkModuleUpdates(request); return ResponseEntity.ok(response); } /** * 下载模块更新包 */ @PostMapping("/download") public ResponseEntity<byte[]> downloadUpdates( @RequestParam String versionCode, @RequestBody List<String> moduleNames) throws IOException { byte[] zipBytes = versionControlService.packageModulesForDownload(moduleNames, versionCode); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"update-" + versionCode + ".zip\"") .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(zipBytes); } }package org.example.bim_design_service.dto; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import lombok.Data; import java.time.LocalDateTime; // ClientModuleInfo.java @Data public class ClientModuleInfo { @NotBlank(message = "模块名称不能为空") private String moduleName; @NotNull(message = "创建时间不能为空") private LocalDateTime createdAt; public ClientModuleInfo() {} } package org.example.bim_design_service.dto; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotEmpty; import lombok.Data; import java.util.List; // ModuleUpdateCheckRequest.java @Data public class ModuleUpdateCheckRequest { @NotBlank(message = "版本号不能为空") private String versionCode; @NotEmpty(message = "模块列表不能为空") private List<ClientModuleInfo> modules; public ModuleUpdateCheckRequest() {} }package org.example.bim_design_service.dto; import lombok.Data; import java.util.List; // ModuleUpdateListResponse.java @Data public class ModuleUpdateListResponse { private String versionCode; private List<ModuleUpdateResponse> updates; } package org.example.bim_design_service.dto; import lombok.Data; import java.time.LocalDateTime; // ModuleUpdateResponse.java @Data public class ModuleUpdateResponse { private String moduleName; private String fileUrl; private String fileHash; private Long fileSize; private LocalDateTime updatedAt; }package org.example.bim_design_service.dto; import com.fasterxml.jackson.annotation.JsonProperty; import jakarta.validation.constraints.NotBlank; import lombok.Data; // VersionCheckRequest.java @Data public class VersionCheckRequest { @JsonProperty("version_code") @NotBlank(message = "版本号不能为空") private String versionCode; public VersionCheckRequest() {} } package org.example.bim_design_service.dto; import lombok.Data; // VersionCheckResponse.java @Data public class VersionCheckResponse { private String versionCode; private boolean needUpdate; } package org.example.bim_design_service.entity; import jakarta.persistence.*; import lombok.Data; import lombok.Getter; import lombok.Setter; import java.time.LocalDateTime; @Entity @Table(name = "module") @Data @Getter @Setter public class FileModule { @Id private String id; @Column(name = "module_name", nullable = false, unique = true) private String moduleName; private String description; @Column(name = "created_at", nullable = false, updatable = false) private LocalDateTime createdAt; @Column(name = "updated_at", nullable = false) private LocalDateTime updatedAt; } package org.example.bim_design_service.entity; import jakarta.persistence.*; import lombok.Data; import lombok.Getter; import lombok.Setter; import java.time.LocalDateTime; @Entity @Table(name = "version") @Data @Getter @Setter public class Version { @Id private String id; @Column(name = "version_code", nullable = false, unique = true) private String versionCode; @Column(name = "release_time", nullable = false) private LocalDateTime releaseTime; private String description; @Column(name = "created_at", nullable = false, updatable = false) private LocalDateTime createdAt; @Column(name = "updated_at", nullable = false) private LocalDateTime updatedAt; public Version(){ } private Version(String id, String versionCode, LocalDateTime releaseTime, String description, LocalDateTime createdAt, LocalDateTime updatedAt) { this.id = id; this.versionCode = versionCode; } } package org.example.bim_design_service.entity; import jakarta.persistence.*; import lombok.Data; import lombok.Getter; import lombok.Setter; import java.time.LocalDateTime; @Entity @Table(name = "version_module") @Data @Getter @Setter public class VersionModule { @Id private String id; @ManyToOne @JoinColumn(name = "version_id", nullable = false) private Version version; @ManyToOne @JoinColumn(name = "module_id", nullable = false) private FileModule module; @Column(name = "file_path", nullable = false) private String filePath; @Column(name = "file_hash", nullable = false) private String fileHash; @Column(name = "file_size", nullable = false) private Long fileSize; @Column(name = "created_at", nullable = false) private LocalDateTime createdAt; @Column(name = "updated_at", nullable = false) private LocalDateTime updatedAt; }package org.example.bim_design_service.repository; import org.example.bim_design_service.entity.FileModule; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Optional; // ModuleRepository.java public interface ModuleRepository extends JpaRepository<FileModule, String> { Optional<FileModule> findByModuleName(String moduleName); }package org.example.bim_design_service.repository; import org.example.bim_design_service.entity.VersionModule; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; import java.util.Optional; // VersionModuleRepository.java public interface VersionModuleRepository extends JpaRepository<VersionModule, String> { List<VersionModule> findByVersionId(String versionId); Optional<VersionModule> findByVersionIdAndModuleId(String versionId, String moduleId); }package org.example.bim_design_service.repository; import org.example.bim_design_service.entity.Version; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Optional; // VersionRepository.java public interface VersionRepository extends JpaRepository<Version, String> { Optional<Version> findTopByOrderByReleaseTimeDesc(); Optional<Version> findByVersionCode(String versionCode); }package org.example.bim_design_service.service; import lombok.RequiredArgsConstructor; import org.example.bim_design_service.dto.*; import org.example.bim_design_service.entity.FileModule; import org.example.bim_design_service.entity.Version; import org.example.bim_design_service.entity.VersionModule; import org.example.bim_design_service.repository.ModuleRepository; import org.example.bim_design_service.repository.VersionModuleRepository; import org.example.bim_design_service.repository.VersionRepository; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; // VersionControlService.java @Service @RequiredArgsConstructor public class VersionControlService { private final VersionRepository versionRepository; private final ModuleRepository moduleRepository; private final VersionModuleRepository versionModuleRepository; @Value("${file.storage.base-url}") private String fileBaseUrl; /** * 检查版本是否需要更新 */ public VersionCheckResponse checkVersion(VersionCheckRequest request) { System.out.println(request.getVersionCode()); // 获取最新版本 Optional<Version> latestVersionOpt = versionRepository.findTopByOrderByReleaseTimeDesc(); if (latestVersionOpt.isEmpty()) { System.out.println(("No version found")); throw new RuntimeException("服务端没有可用的版本"); } Version latestVersion = latestVersionOpt.get(); VersionCheckResponse response = new VersionCheckResponse(); // 比较版本 if (latestVersion.getVersionCode().equals(request.getVersionCode())) { response.setVersionCode(request.getVersionCode()); response.setNeedUpdate(false); } else { response.setVersionCode(latestVersion.getVersionCode()); response.setNeedUpdate(true); } return response; } /** * 检查模块更新 */ public ModuleUpdateListResponse checkModuleUpdates(ModuleUpdateCheckRequest request) { // 验证请求版本是否存在 Version version = versionRepository.findByVersionCode(request.getVersionCode()) .orElseThrow(() -> new RuntimeException("版本不存在")); // 获取该版本的所有模块 List<VersionModule> versionModules = versionModuleRepository.findByVersionId(version.getId()); List<ModuleUpdateResponse> updates = new ArrayList<>(); for (ClientModuleInfo clientModule : request.getModules()) { // 查找模块 Optional<FileModule> moduleOpt = moduleRepository.findByModuleName(clientModule.getModuleName()); if (moduleOpt.isEmpty()) { continue; // 跳过不存在的模块 } FileModule module = moduleOpt.get(); // 查找版本模块关联 Optional<VersionModule> versionModuleOpt = versionModuleRepository .findByVersionIdAndModuleId(version.getId(), module.getId()); if (versionModuleOpt.isPresent()) { VersionModule versionModule = versionModuleOpt.get(); // 检查是否需要更新(客户端模块时间早于服务端) if (clientModule.getCreatedAt().isBefore(versionModule.getCreatedAt())) { ModuleUpdateResponse update = new ModuleUpdateResponse(); update.setModuleName(module.getModuleName()); update.setFileUrl(fileBaseUrl + versionModule.getFilePath()); update.setFileHash(versionModule.getFileHash()); update.setFileSize(versionModule.getFileSize()); update.setUpdatedAt(versionModule.getUpdatedAt()); updates.add(update); } } } ModuleUpdateListResponse response = new ModuleUpdateListResponse(); response.setVersionCode(version.getVersionCode()); response.setUpdates(updates); return response; } /** * 打包模块更新文件为ZIP */ public byte[] packageModulesForDownload(List<String> moduleNames, String versionCode) throws IOException { // 验证版本 Version version = versionRepository.findByVersionCode(versionCode) .orElseThrow(() -> new RuntimeException("版本不存在")); // 创建临时ZIP文件 ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (ZipOutputStream zos = new ZipOutputStream(baos)) { for (String moduleName : moduleNames) { // 查找模块 FileModule module = moduleRepository.findByModuleName(moduleName) .orElseThrow(() -> new RuntimeException("模块不存在: " + moduleName)); // 查找版本模块关联 VersionModule versionModule = versionModuleRepository .findByVersionIdAndModuleId(version.getId(), module.getId()) .orElseThrow(() -> new RuntimeException("模块版本关联不存在")); // 添加文件到ZIP Path filePath = Paths.get(versionModule.getFilePath()); if (Files.exists(filePath)) { ZipEntry entry = new ZipEntry(filePath.getFileName().toString()); zos.putNextEntry(entry); Files.copy(filePath, zos); zos.closeEntry(); } else { throw new RuntimeException("文件不存在: " + filePath); } } } return baos.toByteArray(); } }
最新发布
08-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

spencer_tseng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值