文件管理 · 2024年7月5日

java压缩多个文件夹|如何使用java压缩文件夹成为zip包

❶ pom配置多个jar包压缩成zip

选中多个文件,或者选中那个文件夹按鼠标右键,选择添加到压缩文件,然后取个名字就行。在网络上,有些java程序的提供者将他们的java安装程序打包成一个jar文件的形式。当运行时,自动将jar中的程序解压出来安装到使用者的电脑上。

❷ 用java小应用程序实现文件压缩、解压缩

40.ZIP压缩文件/*import java.io.*;import java.util.zip.*;*///创建文件输入流对象FileInputStream fis=new FileInputStream(%%1);//创建文件输出流对象FileOutputStream fos=new FileOutputStream(%%2);//创建ZIP数据输出流对象ZipOutputStream zipOut=new ZipOutputStream(fos);//创建指向压缩原始文件的入口ZipEntry entry=new ZipEntry(args[0]);zipOut.putNextEntry(entry);//向压缩文件中输出数据int nNumber;byte[] buffer=new byte[1024];while((nNumber=fis.read(buffer))!=-1)zipOut.write(buffer,0,nNumber);//关闭创建的流对象zipOut.close();fos.close();fis.close();}catch(IOException e) {System.out.println(e);} 41.获得应用程序完整路径String %%1=System.getProperty("user.dir");42.ZIP解压缩/*import java.io.*;import java.util.zip.*;*/try{//创建文件输入流对象实例FileInputStream fis=new FileInputStream(%%1);//创建ZIP压缩格式输入流对象实例ZipInputStream zipin=new ZipInputStream(fis);//创建文件输出流对象实例FileOutputStream fos=new FileOutputStream(%%2);//获取Entry对象实例ZipEntry entry=zipin.getNextEntry();byte[] buffer=new byte[1024];int nNumber;while((nNumber=zipin.read(buffer,0,buffer.length))!=-1)fos.write(buffer,0,nNumber);//关闭文件流对象zipin.close();fos.close();fis.close();}catch(IOException e) {System.out.println(e);} 43.递归删除目录中的文件/*import java.io.*;import java.util.*;*/ArrayList<String> folderList = new ArrayList<String>();folderList.add(%%1);for (int j = 0; j < folderList.size(); j++) {File file = new File(folderList.get(j));File[] files = file.listFiles();ArrayList<File> fileList = new ArrayList<File>();for (int i = 0; i < files.length; i++) {if (files[i].isDirectory()) {folderList.add(files[i].getPath());} else {fileList.add(files[i]);}}for (File f : fileList) {f.delete();}} 43.ZIP压缩文件夹/*http://findjar.com/index.jspimport java.io.*;import org.apache.tools.zip.ZipOutputStream; //这个包在ant.jar里,要到官方网下载//java.util.zip.ZipOutputStreamimport java.util.zip.*;*/try {String zipFileName = %%2; //打包后文件名字File f=new File(%%1);ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));String base= "";if (f.isDirectory()) { File[] fl = f.listFiles(); out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/")); base = base.length() == 0 ? "" : base + "/"; for (int i = 0; i < fl.length; i++) { zip(out, fl[i], base + fl[i].getName());}}else { out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); FileInputStream in = new FileInputStream(f); int b; while ( (b = in.read()) != -1) { out.write(b);}in.close();}out.close();}catch (Exception ex) { ex.printStackTrace();} /*切,我刚好写了个压缩的,但没写解压的 1. 解压的(参数两个,第一个是你要解压的zip文件全路径,第二个是你解压之后要存放的位置)/*import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.ZipEntry;import java.util.zip.ZipInputStream;*/public class ZipFileList { public static void main(String[] args) { extZipFileList(args[0],args[1]); } private static void extZipFileList(String zipFileName, String extPlace) { try { ZipInputStream in = new ZipInputStream(new FileInputStream( zipFileName)); ZipEntry entry = null; while ((entry = in.getNextEntry()) != null) { String entryName = entry.getName(); if (entry.isDirectory()) { File file = new File(extPlace + entryName); file.mkdirs(); System.out.println("创建文件夹:" + entryName); } else { FileOutputStream os = new FileOutputStream(extPlace + entryName); // Transfer bytes from the ZIP file to the output file byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { os.write(buf, 0, len); } os.close(); in.closeEntry(); } } } catch (IOException e) { } System.out.println("解压文件成功"); }}压缩的(参数最少传两个,第一个是你压缩之后的文件存放的位置以及名字,第二个是你要压缩的文件或者文件夹所在位置,也可以传多个文件或文件夹)import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.ArrayList;import java.util.Calendar;import java.util.List;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;public class ZipFileOther { public static String zipFileProcess(ArrayList outputZipFileNameList, String outputZipNameAndPath) { ArrayList fileNames = new ArrayList(); ArrayList files = new ArrayList(); FileOutputStream fileOut = null; ZipOutputStream outputStream = null; FileInputStream fileIn = null; StringBuffer sb = new StringBuffer(outputZipNameAndPath); // FileInputStream fileIn =null; try { if (outputZipNameAndPath.indexOf(".zip") != -1) { outputZipNameAndPath = outputZipNameAndPath; } else { sb.append(".zip"); outputZipNameAndPath = sb.toString(); } fileOut = new FileOutputStream(outputZipNameAndPath); outputStream = new ZipOutputStream(fileOut); int outputZipFileNameListSize = 0; if (outputZipFileNameList != null) { outputZipFileNameListSize = outputZipFileNameList.size(); } for (int i = 0; i < outputZipFileNameListSize; i++) { File rootFile = new File(outputZipFileNameList.get(i).toString()); listFile(rootFile, fileNames, files, ""); } for (int loop = 0; loop < files.size(); loop++) { fileIn = new FileInputStream((File) files.get(loop)); outputStream.putNextEntry(new ZipEntry((String) fileNames.get(loop))); byte[] buffer = new byte[1024]; while (fileIn.read(buffer) != -1) { outputStream.write(buffer); } outputStream.closeEntry(); fileIn.close(); } return outputZipNameAndPath; } catch (IOException ioe) { return null; } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { } } if (fileIn != null) { try { fileIn.close(); } catch (IOException e) { } } } } public static void main(String[] args) { ArrayList outputZipFileName=new ArrayList(); String savePath=""; int argSize = 0; if (args != null) { argSize = args.length; } if (argSize > 1) { if(args[0]!=null) savePath = args[0]; for(int i=1;i<argSize;i++){ if(args[i]!=null){ outputZipFileName.add(args[i]); } } ZipFileOther instance=new ZipFileOther(); instance.zipFileProcess(outputZipFileName,savePath); } else { } } private static void listFile(File parentFile, List nameList, List fileList, String directoryName) { if (parentFile.isDirectory()) { File[] files = parentFile.listFiles(); for (int loop = 0; loop < files.length; loop++) { listFile(files[loop], nameList, fileList, directoryName + parentFile.getName() + "/"); } } else { fileList.add(parentFile); nameList.add(directoryName + parentFile.getName()); } }} */

❸ 在java中,gzip 压缩和解压多个文件

直接编译运行!!!不知道你是要查看压缩文件还是要解压文件,所以发上来两个。第一个可以查看各个压缩项目;第二个可以解压文件。import java.awt.*;import java.awt.event.*;import java.io.*;import java.util.*;import java.util.zip.*;import javax.swing.*;import javax.swing.filechooser.FileFilter;class ZipTest { public static void main(String[] args) { ZipTestFrame frame = new ZipTestFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }}class ZipTestFrame extends JFrame { private JComboBox fileCombo; private JTextArea fileText; private String zipname; public ZipTestFrame() { setTitle("ZipTest"); setSize(400,300); JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu("File"); JMenuItem openItem = new JMenuItem("Open"); menu.add(openItem); openItem.addActionListener(new OpenAction()); JMenuItem exitItem = new JMenuItem("Exit"); menu.add(exitItem); exitItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.exit(0); } }); menuBar.add(menu); setJMenuBar(menuBar); fileText = new JTextArea(); fileCombo = new JComboBox(); fileCombo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { loadZipFile((String)fileCombo.getSelectedItem()); } }); add(fileCombo, BorderLayout.SOUTH); add(new JScrollPane(fileText), BorderLayout.CENTER); } public class OpenAction implements ActionListener { public void actionPerformed(ActionEvent event) { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); ExtensionFileFilter filter = new ExtensionFileFilter(); filter.addExtension(".zip"); filter.addExtension(".jar"); filter.setDescription("ZIP archives"); chooser.setFileFilter(filter); int r = chooser.showOpenDialog(ZipTestFrame.this); if(r == JFileChooser.APPROVE_OPTION) { zipname = chooser.getSelectedFile().getPath(); scanZipFile(); } } } public void scanZipFile() { fileCombo.removeAllItems(); try { ZipInputStream zin = new ZipInputStream(new FileInputStream(zipname)); ZipEntry entry; while((entry = zin.getNextEntry()) != null) { fileCombo.addItem(entry.getName()); zin.closeEntry(); } zin.close(); } catch(IOException e) { e.printStackTrace(); } } public void loadZipFile(String name) { try { ZipInputStream zin = new ZipInputStream(new FileInputStream(zipname)); ZipEntry entry; fileText.setText(""); while((entry = zin.getNextEntry()) != null) { if(entry.getName().equals(name)) { BufferedReader in = new BufferedReader(new InputStreamReader(zin)); String line; while((line = in.readLine())!=null) { fileText.append(line); fileText.append("\n"); } } zin.closeEntry(); } zin.close(); } catch(IOException e) { e.printStackTrace(); } } }class ExtensionFileFilter extends FileFilter { private String description = ""; private ArrayList<String>extensions = new ArrayList<String>(); public void addExtension(String extension) { if(!extension.startsWith(".")) extension = "." + extension; extensions.add(extension.toLowerCase()); } public void setDescription(String aDescription) { description = aDescription; } public String getDescription() { return description; } public boolean accept(File f) { if(f.isDirectory()) return true; String name = f.getName().toLowerCase(); for(String e : extensions) if(name.endsWith(e)) return true; return false; } }////////////////////////////////////////////////////////////** *类名:zipFileRelease *说明:一个zip文件解压类 *介绍:主要的zip文件释放方法releaseHandle() * 用ZipInputStream类和ZipEntry类将zip文件的入口清单列举出来,然后 * 根据用户提供的输出路径和zip文件的入口进行组合通过DataOutputStream * 和File类进行文件的创建和目录的创建,创建文件时的文件数据是通过 * ZipInputStream类、ZipEntry类、InputStream类之间的套嵌组合获得的。 *注意:如果zip文件中包含中文路径程序将会抛出异常 */import java.io.*;import java.util.*;import java.util.zip.*;class zipFileRelease{ private String inFilePath; private String releaseFilePath; private String[] FileNameArray; //存放文件名称的数组 private ZipEntry entry; // private FileInputStream fileDataIn; private FileOutputStream fileDataOut; private ZipInputStream zipInFile; private DataOutputStream writeData; private DataInputStream readData; // private int zipFileCount = 0; //zip文件中的文件总数 private int zipPathCount = 0; //zip文件中的路径总数 /** *初始化函数 *初始化zip文件流、输出文件流以及其他变量的初始化 */ public zipFileRelease(String inpath,String releasepath){ inFilePath = inpath; releaseFilePath = releasepath; } /** *初始化读取文件流函数 *参数:FileInputStream类 *返回值:初始化成功返回0,否则返回-1 */ protected long initInStream(ZipInputStream zipFileA){ try{ readData = new DataInputStream(zipFileA); return 0; }catch(Exception e){ e.printStackTrace(); return -1; } } /** *测试文件路径 *参数:zip文件的路径和要释放的位置 *返回值:是两位整数,两位数中的十位代表输入路径和输出路径(1输入、2输出) * 各位数是代表绝对路径还是相对路径(1绝对、0相对) * 返回-1表示路径无效 protected long checkPath(String inPath,String outPath){ File infile = new File(inPath); File infile = new File(outPath); } */ /** *初始化输出文件流 *参数:File类 *返回值:初始化成功返回0,否则返回-1 */ protected long initOutStream(String outFileA){ try{ fileDataOut = new FileOutputStream(outFileA); writeData = new DataOutputStream(fileDataOut); return 0; }catch(IOException e){ e.printStackTrace(); return -1; } } /** *测试文件是否存在方法 *参数:File类 *返回值:如果文件存在返回文件大小,否则返回-1 */ public long checkFile(File inFileA){ if (inFileA.exists()){ return 0; }else{ return -1; } } /** *判断文件是否可以读取方法 *参数:File类 *返回值:如果可以读取返回0,否则返回-1 */ public long checkOpen(File inFileA){ if(inFileA.canRead()){ return inFileA.length(); }else{ return -1; } } /** *获得zip文件中的文件夹和文件总数 *参数:File类 *返回值:如果正常获得则返回总数,否则返回-1 */ public long getFilFoldCount(String infileA){ try{ int fileCount = 0; zipInFile = new ZipInputStream(new FileInputStream(infileA)); while ((entry = zipInFile.getNextEntry()) != null){ if (entry.isDirectory()){ zipPathCount++; }else{ zipFileCount++; } fileCount++; } return fileCount; }catch(IOException e){ e.printStackTrace(); return -1; } } /** *读取zip文件清单函数 *参数:File类 *返回值:文件清单数组 */ public String[] getFileList(String infileA){ try{ ZipInputStream AzipInFile = new ZipInputStream(new FileInputStream(infileA)); //创建数组对象 FileNameArray = new String[(int)getFilFoldCount(infileA)]; //将文件名清单传入数组 int i = 0; while ((entry = AzipInFile.getNextEntry()) != null){ FileNameArray[i++] = entry.getName(); } return FileNameArray; }catch(IOException e){ e.printStackTrace(); return null; } } /** *创建文件函数 *参数:File类 *返回值:如果创建成功返回0,否则返回-1 */ public long writeFile(String outFileA,byte[] dataByte){ try{ if (initOutStream(outFileA) == 0){ writeData.write(dataByte); fileDataOut.close(); return 0; }else{ fileDataOut.close(); return -1; } }catch(IOException e){ e.printStackTrace(); return -1; } } /** *读取文件内容函数 *参数:File类 *返回值:如果读取成功则返回读取数据的字节数组,如果失败则返回空值 */ protected byte[] readFile(ZipEntry entryA,ZipInputStream zipFileA){ try{ long entryFilelen; if (initInStream(zipFileA) == 0){ if ((entryFilelen = entryA.getSize()) >= 0){ byte[] entryFileData = new byte[(int)entryFilelen]; readData.readFully(entryFileData,0,(int)entryFilelen); return entryFileData; }else{ return null; } }else{ return null; } }catch(IOException e){ e.printStackTrace(); return null; } } /** *创建目录函数 *参数:要创建目录的路径 *返回值:如果创建成功则返回0,否则返回-1 */ public long createFolder(String dir){ File file = new File(dir); if (file.mkdirs()) { return 0; }else{ return -1; } } /** *删除文件 *参数:要删除的文件 *返回值:如果删除成功则返回0,要删除的文件不存在返回-2 * 如果要删除的是个路径则返回-3,删除失败则返回-1 */ public long deleteFile(String Apath) throws SecurityException { File file = new File(Apath.trim()); //文件或路径不存在 if (!file.exists()){ return -2; } //要删除的是个路径 if (!file.isFile()){ return -3; } //删除 if (file.delete()){ return 0; }else{ return -1; } } /** *删除目录 *参数:要删除的目录 *返回值:如果删除成功则返回0,删除失败则返回-1 */ public long deleteFolder(String Apath){ File file = new File(Apath); //删除 if (file.delete()){ return 0; }else{ return -1; } } /** *判断所要解压的路径是否存在同名文件 *参数:解压路径 *返回值:如果存在同名文件返回-1,否则返回0 */ public long checkPathExists(String AreleasePath){ File file = new File(AreleasePath); if (!file.exists()){ return 0; }else{ return -1; } } /** *删除zip中的文件 *参数:文件清单数组,释放路径 *返回值:如果删除成功返回0,否则返回-1 */ protected long deleteReleaseZipFile(String[] listFilePath,String releasePath){ long arrayLen,flagReturn; int k = 0; String tempPath; //存放zip文件清单的路径 String[] pathArray = new String[zipPathCount]; //删除文件 arrayLen = listFilePath.length; for(int i=0;i<(int)arrayLen;i++){ tempPath = releasePath.replace('\\','/') + listFilePath[i]; flagReturn = deleteFile(tempPath); if (flagReturn == -2){ //什么都不作 }else if (flagReturn == -3){ pathArray[k++] = tempPath; }else if (flagReturn == -1){ return -1; } } //删除路径 for(k = k – 1;k>=0;k–){ flagReturn = deleteFolder(pathArray[k]); if (flagReturn == -1) return -1; } return 0; } /** *获得zip文件的最上层的文件夹名称 *参数:zip文件路径 *返回值:文件夹名称,如果失败则返回null */ public String getZipRoot(String infileA){ String rootName; try{ FileInputStream tempfile = new FileInputStream(infileA); ZipInputStream AzipInFile = new ZipInputStream(tempfile); ZipEntry Aentry; Aentry = AzipInFile.getNextEntry(); rootName = Aentry.getName(); tempfile.close(); AzipInFile.close(); return rootName; }catch(IOException e){ e.printStackTrace(); return null; } } /** *释放流,释放占用资源 */ protected void closeStream() throws Exception{ fileDataIn.close(); fileDataOut.close(); zipInFile.close(); writeData.flush(); } /** *解压函数 *对用户的zip文件路径和解压路径进行判断,是否存在和打开 *在输入解压路径时如果输入"/"则在和zip文件存放的统计目录下进行解压 *返回值:0表示释放成功 * -1 表示您所要解压的文件不存在、 * -2表示您所要解压的文件不能被打开、 * -3您所要释放的路径不存在、 * -4您所创建文件目录失败、 * -5写入文件失败、 * -6表示所要释放的文件已经存在、 * -50表示文件读取异常 */ public long releaseHandle() throws Exception{ File inFile = new File(inFilePath); File outFile = new File(releaseFilePath); String tempFile; String zipPath; String zipRootPath; String tempPathParent; //存放释放路径 byte[] zipEntryFileData; //作有效性判断 if (checkFile(inFile) == -1) { return -1;} if (checkOpen(inFile) == -1) { return -2;} //不是解压再当前目录下时对路径作有效性检验 if (!releaseFilePath.equals("/")){ //解压在用户指定目录下 if (checkFile(outFile) == -1) { return -3;} } //获得标准释放路径 if (!releaseFilePath.equals("/")) { tempPathParent = releaseFilePath.replace('\\','/')+ "/"; }else{ tempPathParent = inFile.getParent().replace('\\','/')+ "/"; } //获得zip文件中的入口清单 FileNameArray = getFileList(inFilePath); //获得zip文件的最上层目录 zipRootPath = getZipRoot(inFilePath); // fileDataIn = new FileInputStream(inFilePath); zipInFile = new ZipInputStream(fileDataIn); //判断是否已经存在要释放的文件夹 if (zipRootPath.lastIndexOf("/") > 0 ){ if (checkPathExists(tempPathParent + zipRootPath.substring(0,zipRootPath.lastIndexOf("/"))) == -1){ return -6; } }else{ if (checkPathExists(tempPathParent + zipRootPath) == -1){ return -6; } } // try{ //创建文件夹和文件 int i = 0; while ((entry = zipInFile.getNextEntry()) != null){ if (entry.isDirectory()){ //创建目录 zipPath = tempPathParent + FileNameArray[i]; zipPath = zipPath.substring(0,zipPath.lastIndexOf("/")); if (createFolder(zipPath) == -1){ closeStream(); deleteReleaseZipFile(FileNameArray,tempPathParent); return -4; } }else{ //读取文件数据 zipEntryFileData = readFile(entry,zipInFile); //向文件写数据 tempFile = tempPathParent + FileNameArray[i]; //写入文件 if (writeFile(tempFile,zipEntryFileData) == -1){ closeStream(); deleteReleaseZipFile(FileNameArray,tempPathParent); return -5; } } i++; } //释放资源 closeStream(); return 0; }catch(Exception e){ closeStream(); deleteReleaseZipFile(FileNameArray,tempPathParent); e.printStackTrace(); return -50; } } /** *演示函数 *根据用户输入的路径对文件进行解压 */ public static void main(String args[]) throws Exception { long flag; //返回标志 String inPath,releasePath; //获得用户输入信息 BufferedReader userInput = new BufferedReader( new InputStreamReader(System.in)); System.out.println("请输入zip文件路径:"); inPath = userInput.readLine(); System.out.println("请输入保存路径:"); releasePath = userInput.readLine(); userInput.close(); //执行解压缩 zipFileRelease pceraZip = new zipFileRelease(inPath,releasePath); flag = pceraZip.releaseHandle(); //出错信息打印 if (flag == 0) System.out.println("释放成功!!!"); if (flag == -1) System.out.println("您所要解压的文件不存在!"); if (flag == -2) System.out.println("您所要解压的文件不能被打开!"); if (flag == -3) System.out.println("您所要释放的路径不存在!"); if (flag == -4) System.out.println("您所创建文件目录失败!"); if (flag == -5) System.out.println("写入文件失败!"); if (flag == -6) System.out.println("文件已经存在!"); if (flag == -50) System.out.println("文件读取异常!"); }}

❹ JAVA 压缩和序列化

压缩和序列化主要用在数据的存储和传输上,二者都是由IO流相关知识实现,这里统一介绍下。

全部章节传送门:

Java I/O类支持读写压缩格式的数据流,你可以用他们对其他的I/O流进行封装,以提供压缩功能。

GZIP接口比较简单,适合对单个数据流进行压缩,在Linux系统中使用较多。

ZIP格式可以压缩多个文件,而且可以和压缩工具进行协作,是经常使用的压缩方法。

JAR(Java Archive,Java 归档文件)是与平台无关的文件格式,它允许将许多文件组合成一个压缩文件。为 J2EE 应用程序创建的 JAR 文件是 EAR 文件(企业 JAR 文件)。

JAR 文件格式以流行的 ZIP 文件格式为基础。与 ZIP 文件不同的是,JAR 文件不仅用于压缩和发布,而且还用于部署和封装库、组件和插件程序,并可被像编译器和 JVM 这样的工具直接使用。在 JAR 中包含特殊的文件,如 manifests 和部署描述符,用来指示工具如何处理特定的 JAR。

如果一个Web应用程序的目录和文件非常多,那么将这个Web应用程序部署到另一台机器上,就不是很方便了,我们可以将Web应用程序打包成Web 归档(WAR)文件,这个过程和把Java类文件打包成JAR文件的过程类似。利用WAR文件,可以把Servlet类文件和相关的资源集中在一起进行发布。在这个过程中,Web应用程序就不是按照目录层次结构来进行部署了,而是把WAR文件作为部署单元来使用。

一个WAR文件就是一个Web应用程序,建立WAR文件,就是把整个Web应用程序(不包括Web应用程序层次结构的根目录)压缩起来,指定一个.war扩展名。下面我们将第2章的Web应用程序打包成WAR文件,然后发布

要注意的是,虽然WAR文件和JAR文件的文件格式是一样的,并且都是使用jar命令来创建,但就其应用来说,WAR文件和JAR文件是有根本区别的。JAR文件的目的是把类和相关的资源封装到压缩的归档文件中,而对于WAR文件来说,一个WAR文件代表了一个Web应用程序,它可以包含 Servlet、HTML页面、Java类、图像文件,以及组成Web应用程序的其他资源,而不仅仅是类的归档文件。

在命令行输入jar即可查看jar命令的使用方法。

把对象转换为字节序列的过程称为对象的序列化。把字节序列恢复为对象的过程称为对象的反序列化。

对象的序列化主要有两种用途:

java.io.ObjectOutputStream代表对象输出流,它的writeObject(Object obj)方法可对参数指定的obj对象进行序列化,把得到的字节序列写到一个目标输出流中。

java.io.ObjectInputStream代表对象输入流,它的readObject()方法从一个源输入流中读取字节序列,再把它们反序列化为一个对象,并将其返回。

只有实现了Serializable的对象才能被序列化。对象序列化包括如下步骤:

对象反序列化的步骤如下:

创建一个可以可以序列化的对象。

然后进行序列化和反序列化测试。

s​e​r​i​a​l​V​e​r​s​i​o​n​U​I​D​:​ ​字​面​意​思​上​是​序​列​化​的​版​本​号​,凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态变量。

JAVA序列化的机制是通过判断类的serialVersionUID来验证的版本一致的。在进行反序列化时,JVM会把传来的字节流中的serialVersionUID于本地相应实体类的serialVersionUID进行比较。如果相同说明是一致的,可以进行反序列化,否则会出现反序列化版本一致的异常,即是InvalidCastException。

为了提高serialVersionUID的独立性和确定性,强烈建议在一个可序列化类中显示的定义serialVersionUID,为它赋予明确的值。

控制序列化字段还可以使用Externalizable接口替代Serializable借口。此时需要定义一个默认构造器,否则将为得到一个异常(java.io.InvalidClassException: Person; Person; no valid constructor);还需要定义两个方法(writeExternal()和readExternal())来控制要序列化的字段。

如下为将Person类修改为使用Externalizable接口。

transient修饰符仅适用于变量,不适用于方法和类。在序列化时,如果我们不想序列化特定变量以满足安全约束,那么我们应该将该变量声明为transient。执行序列化时,JVM会忽略transient变量的原始值并将默认值(引用类型就是null,数字就是0)保存到文件中。因此,transient意味着不要序列化。

静态变量不是对象状态的一部分,因此它不参与序列化。所以将静态变量声明为transient变量是没有用处的。

❺ java ZipOutputStream 压缩包里面压缩多个文件(格式为zip文件)

在压缩包里运行文件都是制动解压到临时文件夹临时文件夹在C盘所以还是建议正常解压后再运行在有些情况下直接在压缩包里运行文件有些程序还未解压到临时文件夹所以就会报错手动解压在运行是最好的以,下是临时文件夹的路径C:\Documents and Settings\Administrator\Local Settings\Temp

❻ java中将一个文件夹下所有的文件压缩成一个文件,然后,解压到指定目录.

import java.io.*;import java.util.zip.*;public class CompressD { // 缓冲 static byte[] buffer = new byte[2048]; public static void main(String[] args) throws Exception { // 来源 File inputDir = new File("C:\\CompressTest\\"); // 目标 FileOutputStream fos = new FileOutputStream("C:\\CompressTest.zip"); // 过滤 ZipOutputStream zos = new ZipOutputStream(fos); // 压缩 zip(inputDir.listFiles(), "", zos); // 关闭 zos.close(); } private static void zip(File[] files, String baseFolder, ZipOutputStream zos) throws Exception { // 输入 FileInputStream fis = null; // 条目 ZipEntry entry = null; // 数目 int count = 0; for (File file : files) { if (file.isDirectory()) { // 递归 zip(file.listFiles(), file.getName() + File.separator, zos); continue; } entry = new ZipEntry(baseFolder + file.getName()); // 加入 zos.putNextEntry(entry); fis = new FileInputStream(file); // 读取 while ((count = fis.read(buffer, 0, buffer.length)) != -1) // 写入 zos.write(buffer, 0, count); } }}

❼ 如何使用java压缩文件夹成为zip包

在JDK中有一个zip工具类:

java.util.zip Provides classes for reading and writing the standard ZIP and GZIP file formats.

使用此类可以将文件夹或者多个文件进行打包压缩操作。

在使用之前先了解关键方法:

ZipEntry(String name) Creates a new zip entry with the specified name.

使用ZipEntry的构造方法可以创建一个zip压缩文件包的实例,然后通过ZipOutputStream将待压缩的文件以流的形式写进该压缩包中。具体实现代码如下:

importjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.util.zip.ZipEntry;importjava.util.zip.ZipOutputStream;/***将文件夹下面的文件*打包成zip压缩文件**@authoradmin**/publicfinalclassFileToZip{privateFileToZip(){}/***将存放在sourceFilePath目录下的源文件,打包成fileName名称的zip文件,并存放到zipFilePath路径下*@paramsourceFilePath:待压缩的文件路径*@paramzipFilePath:压缩后存放路径*@paramfileName:压缩后文件的名称*@return*/publicstaticbooleanfileToZip(StringsourceFilePath,StringzipFilePath,StringfileName){booleanflag=false;FilesourceFile=newFile(sourceFilePath);FileInputStreamfis=null;BufferedInputStreambis=null;FileOutputStreamfos=null;ZipOutputStreamzos=null;if(sourceFile.exists()==false){System.out.println("待压缩的文件目录:"+sourceFilePath+"不存在.");}else{try{FilezipFile=newFile(zipFilePath+"/"+fileName+".zip");if(zipFile.exists()){System.out.println(zipFilePath+"目录下存在名字为:"+fileName+".zip"+"打包文件.");}else{File[]sourceFiles=sourceFile.listFiles();if(null==sourceFiles||sourceFiles.length<1){System.out.println("待压缩的文件目录:"+sourceFilePath+"里面不存在文件,无需压缩.");}else{fos=newFileOutputStream(zipFile);zos=newZipOutputStream(newBufferedOutputStream(fos));byte[]bufs=newbyte[1024*10];for(inti=0;i<sourceFiles.length;i++){//创建ZIP实体,并添加进压缩包ZipEntryzipEntry=newZipEntry(sourceFiles[i].getName());zos.putNextEntry(zipEntry);//读取待压缩的文件并写进压缩包里fis=newFileInputStream(sourceFiles[i]);bis=newBufferedInputStream(fis,1024*10);intread=0;while((read=bis.read(bufs,0,1024*10))!=-1){zos.write(bufs,0,read);}}flag=true;}}}catch(FileNotFoundExceptione){e.printStackTrace();thrownewRuntimeException(e);}catch(IOExceptione){e.printStackTrace();thrownewRuntimeException(e);}finally{//关闭流try{if(null!=bis)bis.close();if(null!=zos)zos.close();}catch(IOExceptione){e.printStackTrace();thrownewRuntimeException(e);}}}returnflag;}publicstaticvoidmain(String[]args){StringsourceFilePath="D:\TestFile";StringzipFilePath="D:\tmp";StringfileName="12700153file";booleanflag=FileToZip.fileToZip(sourceFilePath,zipFilePath,fileName);if(flag){System.out.println("文件打包成功!");}else{System.out.println("文件打包失败!");}}}

❽ java压缩文件的问题

有三种方式实现java压缩:1、jdk自带的包java.util.zip.ZipOutputStream,不足之处,文件(夹)名称带中文时,出现乱码问题,实现代码如下:/** * 功能:把 sourceDir 目录下的所有文件进行 zip 格式的压缩,保存为指定 zip 文件 * @param sourceDir 如果是目录,eg:D:\\MyEclipse\\first\\testFile,则压缩目录下所有文件; * 如果是文件,eg:D:\\MyEclipse\\first\\testFile\\aa.zip,则只压缩本文件 * @param zipFile 最后压缩的文件路径和名称,eg:D:\\MyEclipse\\first\\testFile\\aa.zip */ public File doZip(String sourceDir, String zipFilePath) throws IOException { File file = new File(sourceDir); File zipFile = new File(zipFilePath); ZipOutputStream zos = null; try { // 创建写出流操作 OutputStream os = new FileOutputStream(zipFile); BufferedOutputStream bos = new BufferedOutputStream(os); zos = new ZipOutputStream(bos); String basePath = null; // 获取目录 if(file.isDirectory()) { basePath = file.getPath(); }else { basePath = file.getParent(); } zipFile(file, basePath, zos); }finally { if(zos != null) { zos.closeEntry(); zos.close(); } } return zipFile; } /** * @param source 源文件 * @param basePath * @param zos */ private void zipFile(File source, String basePath, ZipOutputStream zos) throws IOException { File[] files = null; if (source.isDirectory()) { files = source.listFiles(); } else { files = new File[1]; files[0] = source; } InputStream is = null; String pathName; byte[] buf = new byte[1024]; int length = 0; try{ for(File file : files) { if(file.isDirectory()) { pathName = file.getPath().substring(basePath.length() + 1) + "/"; zos.putNextEntry(new ZipEntry(pathName)); zipFile(file, basePath, zos); }else { pathName = file.getPath().substring(basePath.length() + 1); is = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(is); zos.putNextEntry(new ZipEntry(pathName)); while ((length = bis.read(buf)) > 0) { zos.write(buf, 0, length); } } } }finally { if(is != null) { is.close(); } } }2、使用org.apache.tools.zip.ZipOutputStream,代码如下, package net.szh.zip; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.zip.CRC32; import java.util.zip.CheckedOutputStream; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipOutputStream; public class ZipCompressor { static final int BUFFER = 8192; private File zipFile; public ZipCompressor(String pathName) { zipFile = new File(pathName); } public void compress(String srcPathName) { File file = new File(srcPathName); if (!file.exists()) throw new RuntimeException(srcPathName + "不存在!"); try { FileOutputStream fileOutputStream = new FileOutputStream(zipFile); CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32()); ZipOutputStream out = new ZipOutputStream(cos); String basedir = ""; compress(file, out, basedir); out.close(); } catch (Exception e) { throw new RuntimeException(e); } } private void compress(File file, ZipOutputStream out, String basedir) { /* 判断是目录还是文件 */ if (file.isDirectory()) { System.out.println("压缩:" + basedir + file.getName()); this.compressDirectory(file, out, basedir); } else { System.out.println("压缩:" + basedir + file.getName()); this.compressFile(file, out, basedir); } } /** 压缩一个目录 */ private void compressDirectory(File dir, ZipOutputStream out, String basedir) { if (!dir.exists()) return; File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { /* 递归 */ compress(files[i], out, basedir + dir.getName() + "/"); } } /** 压缩一个文件 */ private void compressFile(File file, ZipOutputStream out, String basedir) { if (!file.exists()) { return; } try { BufferedInputStream bis = new BufferedInputStream( new FileInputStream(file)); ZipEntry entry = new ZipEntry(basedir + file.getName()); out.putNextEntry(entry); int count; byte data[] = new byte[BUFFER]; while ((count = bis.read(data, 0, BUFFER)) != -1) { out.write(data, 0, count); } bis.close(); } catch (Exception e) { throw new RuntimeException(e); } } } 3、可以用ant中的org.apache.tools.ant.taskdefs.Zip来实现,更加简单。 package net.szh.zip; import java.io.File; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Zip; import org.apache.tools.ant.types.FileSet; public class ZipCompressorByAnt { private File zipFile; public ZipCompressorByAnt(String pathName) { zipFile = new File(pathName); } public void compress(String srcPathName) { File srcdir = new File(srcPathName); if (!srcdir.exists()) throw new RuntimeException(srcPathName + "不存在!"); Project prj = new Project(); Zip zip = new Zip(); zip.setProject(prj); zip.setDestFile(zipFile); FileSet fileSet = new FileSet(); fileSet.setProject(prj); fileSet.setDir(srcdir); //fileSet.setIncludes("**/*.java"); 包括哪些文件或文件夹 eg:zip.setIncludes("*.java"); //fileSet.setExcludes(…); 排除哪些文件或文件夹 zip.addFileset(fileSet); zip.execute(); } } 测试一下 package net.szh.zip; public class TestZip { public static void main(String[] args) { ZipCompressor zc = new ZipCompressor("E:\\szhzip.zip"); zc.compress("E:\\test"); ZipCompressorByAnt zca = new ZipCompressorByAnt("E:\\szhzipant.zip"); zca.compress("E:\\test"); } }

❾ java怎么实现遍历文件夹并压缩的功能

不考虑一个文件夹下有另外一个文件夹的情况下,代码如下

publicstaticvoidZipFolder(Filedirectory)throwsException{FileOutputStreamfout=newFileOutputStream("输出压缩文件test.zip的位置");ZipOutputStreamzout=newZipOutputStream(fout);for(Filefile:directory.listFiles()){byte[]buffer=Files.readAllBytes(file.toPath());ZipEntryzipEntry=newZipEntry(file.getName());zout.putNextEntry(zipEntry);zout.write(buffer);zout.closeEntry();}zout.flush();zout.close();}