文件管理 · 2022年9月14日

java解析压缩文件|java中怎么用cmd命令解压zip文件

❶ java如何解压页面上传到服务器的zip文件

这个转换肯定是会出错的,struts 的formFile跟zipFile没有直接关系,怎么能这么强制转化呢?建议1. 把文件保存到一个临时目录(保存为zip文件)2. 读取这个文件3. 抽取想要的文件4. 把临时文件删除

❷ java如何解压.gz后缀的压缩包

File file = new File(zipFilePath); 将zip文件路径转换 成文件

zipFile = new ZipFile(file); 调用java util下面的zipfile类

Enumeration<?> zipEnum = zipFile.entries(); 将zip文件里面的内容都放在迭代器里面了

ZipEntry entry = (ZipEntry) zipEnum.nextElement();,然后迭代出ZipEntry对象。

zipFile.getInputStream(entry)就可以得到所需要的流了,之后做你需要的操作。

❸ java如何直接解压zip格式二进制流

Java代码import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.util.zip.ZipEntry;import java.util.zip.ZipInputStream;import java.util.zip.ZipOutputStream;class ZipTest {// 压缩public static void zip(String zipFileName, String inputFile)throws Exception {File f = new File(inputFile);ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));zip(out, f, f.getName());System.out.println("zip done");out.close();

❹ java解压zip文件

import java.io.IOException;import java.util.Enumeration;import java.util.zip.ZipEntry;/** * 获得zip文件里的所有文件 * @author Administrator * */public class ZipFile { public ZipFile() throws IOException { java.util.zip.ZipFile zf = new java.util.zip.ZipFile("E:/Java/Project.zip"); Enumeration e = zf.entries(); while(e.hasMoreElements()) { ZipEntry ze = (ZipEntry) e.nextElement(); if(!ze.isDirectory()) System.out.println(new String(ze.getName().getBytes("ISO-8859-1"), "GB2312")); } } public static void main(String[] args) { try { new ZipFile(); } catch (IOException e) { e.printStackTrace(); } }}

❺ Java压缩与解压缩问题

/** *类名:zipFileRelease *说明:一个zip文件解压类 *介绍:主要的zip文件释放方法releaseHandle() * 用ZipInputStream类和ZipEntry类将zip文件的入口清单列举出来,然后 * 根据用户提供的输出路径和zip文件的入口进行组合通过DataOutputStream * 和File类进行文件的创建和目录的创建,创建文件时的文件数据是通过 * ZipInputStream类、ZipEntry类、InputStream类之间的套嵌组合获得的。 *注意:如果zip文件中包含中文路径程序将会抛出异常 *日期:2005-7-1 *作者:Pcera */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怎么读取Zip和RAR里面的文件啊

ZipInputStream是一个指向ZIP文件的流,这个流最重要的方法就是getNextEntry方法,一个zip文件可以包含好几个被压缩的文件,这个方法的功能就是返回下一个目录项,也就是返回zip文件中的下一项,并且把流指向这个目录文件项。getNextEntry的返回值是ZipEntry,它表示zip文件中的一个项,它可以返回这个文件项的大小、名称等。你可以根据它返回的文件大小调用ZipInputStream的read方法来读取需要的字节。给你一个例子:public class ZipTest { public static void main(String args[]) throws FileNotFoundException, IOException{ ZipInputStream zis = new ZipInputStream(new FileInputStream ("c://a.zip"));//生成读取ZIP文件的流 ZipEntry ze = zis.getNextEntry();//取得下一个文件项 long size = ze.getSize();//取得这一项的大小 FileOutputStream fos = new FileOutputStream("c://"+ze.getName());//产生输出文件对象 for(int i= 0;i<size;i++){//循环读取文件并写入输出文件对象 byte c = (byte)zis.read(); fos.write(c); } fos.close(); zis.close(); }}

❼ java如何读取压缩包中的文本文件

压缩包的里的文件不能直接读取,只能先解压缩,再读取。建议:可以用apache的工具类,先解压缩成临时文件,再读取,最后删除临时文件。

❽ 怎样用java快速实现zip文件的压缩解压缩

packagezip;importjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.util.Enumeration;importjava.util.zip.CRC32;importjava.util.zip.CheckedOutputStream;importjava.util.zip.ZipEntry;importjava.util.zip.ZipFile;importjava.util.zip.ZipOutputStream;importorg.apache.commons.lang3.StringUtils;publicclassZipUtil{/***递归压缩文件夹*@paramsrcRootDir压缩文件夹根目录的子路径*@paramfile当前递归压缩的文件或目录对象*@paramzos压缩文件存储对象*@throwsException*/privatestaticvoidzip(StringsrcRootDir,Filefile,ZipOutputStreamzos)throwsException{if(file==null){return;}//如果是文件,则直接压缩该文件if(file.isFile()){intcount,bufferLen=1024;bytedata[]=newbyte[bufferLen];//获取文件相对于压缩文件夹根目录的子路径StringsubPath=file.getAbsolutePath();intindex=subPath.indexOf(srcRootDir);if(index!=-1){subPath=subPath.substring(srcRootDir.length()+File.separator.length());}ZipEntryentry=newZipEntry(subPath);zos.putNextEntry(entry);BufferedInputStreambis=newBufferedInputStream(newFileInputStream(file));while((count=bis.read(data,0,bufferLen))!=-1){zos.write(data,0,count);}bis.close();zos.closeEntry();}//如果是目录,则压缩整个目录else{//压缩目录中的文件或子目录File[]childFileList=file.listFiles();for(intn=0;n<childFileList.length;n++){childFileList[n].getAbsolutePath().indexOf(file.getAbsolutePath());zip(srcRootDir,childFileList[n],zos);}}}/***对文件或文件目录进行压缩*@paramsrcPath要压缩的源文件路径。如果压缩一个文件,则为该文件的全路径;如果压缩一个目录,则为该目录的顶层目录路径*@paramzipPath压缩文件保存的路径。注意:zipPath不能是srcPath路径下的子文件夹*@paramzipFileName压缩文件名*@throwsException*/publicstaticvoidzip(StringsrcPath,StringzipPath,StringzipFileName)throwsException{if(StringUtils.isEmpty(srcPath)||StringUtils.isEmpty(zipPath)||StringUtils.isEmpty(zipFileName)){thrownewParameterException(ICommonResultCode.PARAMETER_IS_NULL);}CheckedOutputStreamcos=null;ZipOutputStreamzos=null;try{FilesrcFile=newFile(srcPath);//判断压缩文件保存的路径是否为源文件路径的子文件夹,如果是,则抛出异常(防止无限递归压缩的发生)if(srcFile.isDirectory()&&zipPath.indexOf(srcPath)!=-1){thrownewParameterException(ICommonResultCode.INVALID_PARAMETER,".");}//判断压缩文件保存的路径是否存在,如果不存在,则创建目录FilezipDir=newFile(zipPath);if(!zipDir.exists()||!zipDir.isDirectory()){zipDir.mkdirs();}//创建压缩文件保存的文件对象StringzipFilePath=zipPath+File.separator+zipFileName;FilezipFile=newFile(zipFilePath);if(zipFile.exists()){//检测文件是否允许删除,如果不允许删除,将会抛出SecurityException=newSecurityManager();securityManager.checkDelete(zipFilePath);//删除已存在的目标文件zipFile.delete();}cos=newCheckedOutputStream(newFileOutputStream(zipFile),newCRC32());zos=newZipOutputStream(cos);//如果只是压缩一个文件,则需要截取该文件的父目录StringsrcRootDir=srcPath;if(srcFile.isFile()){intindex=srcPath.lastIndexOf(File.separator);if(index!=-1){srcRootDir=srcPath.substring(0,index);}}//调用递归压缩方法进行目录或文件压缩zip(srcRootDir,srcFile,zos);zos.flush();}catch(Exceptione){throwe;}finally{try{if(zos!=null){zos.close();}}catch(Exceptione){e.printStackTrace();}}}/***解压缩zip包*@paramzipFilePathzip文件的全路径*@paramunzipFilePath解压后的文件保存的路径*@paramincludeZipFileName解压后的文件保存的路径是否包含压缩文件的文件名。true-包含;false-不包含*/@SuppressWarnings("unchecked")publicstaticvoinzip(StringzipFilePath,StringunzipFilePath,booleanincludeZipFileName)throwsException{if(StringUtils.isEmpty(zipFilePath)||StringUtils.isEmpty(unzipFilePath)){thrownewParameterException(ICommonResultCode.PARAMETER_IS_NULL);}FilezipFile=newFile(zipFilePath);//如果解压后的文件保存路径包含压缩文件的文件名,则追加该文件名到解压路径if(includeZipFileName){StringfileName=zipFile.getName();if(StringUtils.isNotEmpty(fileName)){fileName=fileName.substring(0,fileName.lastIndexOf("."));}unzipFilePath=unzipFilePath+File.separator+fileName;}//创建解压缩文件保存的路径FileunzipFileDir=newFile(unzipFilePath);if(!unzipFileDir.exists()||!unzipFileDir.isDirectory()){unzipFileDir.mkdirs();}//开始解压ZipEntryentry=null;StringentryFilePath=null,entryDirPath=null;FileentryFile=null,entryDir=null;intindex=0,count=0,bufferSize=1024;byte[]buffer=newbyte[bufferSize];BufferedInputStreambis=null;BufferedOutputStreambos=null;ZipFilezip=newZipFile(zipFile);Enumeration<ZipEntry>entries=(Enumeration<ZipEntry>)zip.entries();//循环对压缩包里的每一个文件进行解压while(entries.hasMoreElements()){entry=entries.nextElement();//构建压缩包中一个文件解压后保存的文件全路径entryFilePath=unzipFilePath+File.separator+entry.getName();//构建解压后保存的文件夹路径index=entryFilePath.lastIndexOf(File.separator);if(index!=-1){entryDirPath=entryFilePath.substring(0,index);}else{entryDirPath="";}entryDir=newFile(entryDirPath);//如果文件夹路径不存在,则创建文件夹if(!entryDir.exists()||!entryDir.isDirectory()){entryDir.mkdirs();}//创建解压文件entryFile=newFile(entryFilePath);if(entryFile.exists()){//检测文件是否允许删除,如果不允许删除,将会抛出SecurityException=newSecurityManager();securityManager.checkDelete(entryFilePath);//删除已存在的目标文件entryFile.delete();}//写入文件bos=newBufferedOutputStream(newFileOutputStream(entryFile));bis=newBufferedInputStream(zip.getInputStream(entry));while((count=bis.read(buffer,0,bufferSize))!=-1){bos.write(buffer,0,count);}bos.flush();bos.close();}}publicstaticvoidmain(String[]args){StringzipPath="d:\ziptest\zipPath";Stringdir="d:\ziptest\rawfiles";StringzipFileName="test.zip";try{zip(dir,zipPath,zipFileName);}catch(Exceptione){e.printStackTrace();}StringzipFilePath="D:\ziptest\zipPath\test.zip";StringunzipFilePath="D:\ziptest\zipPath";try{unzip(zipFilePath,unzipFilePath,true);}catch(Exceptione){e.printStackTrace();}}}

❾ java Zip解析乱码问题

debug一下,看看filepath输出什么,看看下面这个代码import java.io.*; import java.util.zip.*; public class Zip { static final int BUFFER = 2048; static boolean flag = false; public static void main(String args[])throws IOException{ File file= new File("D:/Temp"); ZipSubdirectory(file); FileInputStream file1 = new FileInputStream(ZipSubdirectory(file)); System.out.println(file1.toString()); } //ZipSubdirectory函数将一个指定目录(包括它子目录)压缩成一个同名压缩文件(这里称为"ORIGIN") public static File ZipSubdirectory(File myDir)throws IOException{ //创建缓冲输入流BufferedInputStream BufferedInputStream origin = null; //创建ZipOutputStream对象,将向它传递希望写入文件的输出流 File zipFile=new File("D:/"+myDir.getName()+".zip"); FileOutputStream fos=new FileOutputStream(zipFile); ZipOutputStream out=new ZipOutputStream(new BufferedOutputStream(fos,BUFFER)); //dirContents[]获取当前目录(myDir)所有文件对象(包括子目录名) File dirContents[]=myDir.listFiles(); //创建临时文件tempFile,使用后删除 File tempFile=null; try{ //处理当前目录所有文件对象,包括子目录 for(int i=0;i < dirContents.length; i++){ //使用递归方法将当前目录的子目录转成一个ZIP文件,并作为一个ENTRY加进"ORIGIN" if(dirContents[i].isDirectory()){ tempFile = ZipSubdirectory(dirContents[i]); flag=true; } //如果当前文件不是子目录 else { tempFile=dirContents[i]; //flag标记tempFile是否由子目录压缩成的ZIP文件 flag = false; } System.out.println("Compress file: "+tempFile.getName()); FileInputStream fis = new FileInputStream(tempFile); origin = new BufferedInputStream(fis,BUFFER); //为被读取的文件创建压缩条目 ZipEntry entry = new ZipEntry(tempFile.getName()); byte data[]= new byte[BUFFER]; int count; //在向ZIP输出流写入数据之前,必须首先使用out.putNextEntry(entry); 方法安置压缩条目对象 out.putNextEntry(entry); //向ZIP 文件写入数据 while((count=origin.read(data,0,BUFFER))!=-1){ out.write(data,0,count); } //tempFile是临时生成的ZIP文件,删除它 if(flag==true){ flag = tempFile.delete(); System.out.println("Delete file:"+tempFile.getName()+flag); } //关闭输入流 origin.close(); } out.close(); } catch(Exception e){ System.out.println(e); } //递归返回 return zipFile; } } 来自

❿ java中怎么用cmd命令解压zip文件

对于zip文件,java有自带类库java.util.zip;可是要想解压rar文件只能靠第三方类库,我试过两个:com.github.junrar和de.innosystec.unrar,前者解压时可能会出现crcError,后者pom配置时报错;利用cmd命令调用winRAR进行解压,无疑方便快捷很多。

调用cmd命令

public static boolean exe(String cmd) {Runtime runtime = Runtime.getRuntime(); try {Process p = runtime.exec(cmd);BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream(),"GBK"));String line = reader.readLine(); while(line!=null) {logger.info(line);line = reader.readLine();}reader.close(); if(p.waitFor()!=0) { return false;}} catch (IOException e) { // TODO Auto-generated catch blocke.printStackTrace();} catch (InterruptedException e) { // TODO Auto-generated catch blocke.printStackTrace();} return true;}

首先利用runtime.exec()执行指令,得到process,从process.getInputStream()中获取回显字符并打印,打印回显时可能会出现中文乱码,这个和操作系统编码有关,我这里是GBK编码,所以在new inputstreamReader时加入了编码参数”GBK“

命令行字符串

如果需要调用cmd命令,如cd等,可写”cmd c cd 目录”。对于直接调用exe执行,则可以写成”exe文件绝对路径 参数”,在命令行字符串中,含有空格的路径或者字符串应该再加上引号,即””exe文件绝对路径” ”参数”“

winRAR调用

我这里安装目录是C:/Program Files/WinRAR,将D:1.rar 解压到D:,则写成””C:/Program Files/WinRAR/unRar.exe” x -y D:/1.rar D:/”,x代表绝对路径解压,-y表示全部确定;压缩的命令如下:“”C:/Program Files/WinRAR/rar.exe” a -ep1 D:2.rar D:源目录”,a表示添加文件到压缩文件,-ep1表示排除基本目录,如D:winrarar这个目录,如果没有-ep1那么压缩包中会出现winrar目录路径,而加了之后就只将当前目录打包,只有rar目录