Java培训笔记二十一()
2010年12月13日
特殊流类型:
1,RandomAccessFile
2,压缩与解压:zip/rar,jar,Gzip
(1)zip:zipOutputStream
DataOutputStream
zipEntry
(2)GZip:GZipOutputStream
(3)jar:JarOutputStream
JarEntry
Attribute
3,管道流:PipedInputstream
PipedOutputstream
import java.io.*;
import java.util.zip.*;
/** *//**
*功能:zip压缩、解压
*说明:本程序通过ZipOutputStream和ZipInputStream实现了zip压缩和解压功能.
*问题:由于java.util.zip包并不支持汉字,当zip文件中有名字为中文的文件时
, author by http://www.bt285.cn http://www.5a520.cn
* 就会出现异常:"Exception in thread "main " java.lang.IllegalArgumentException
* at java.util.zip.ZipInputStream.getUTF8String(ZipInpu tStream.java:285)
*解决:
* 方法1、修改import java.util.zip.ZipInputStream和ZipOutputStream.
* java.util.zip只支持UTF-8,Ant里面可以指定编码.
* 方法2、使用Apache Ant里提供的zip工具。
* 不使用java.util.zip的包,把ant.jar放到classpath中.
* 程序中使用import org.apache.tools.zip.*;
*
*仅供编程学习参考.
*
*@author Winty
*@date 2008-8-3
*@Usage:
* 压缩:java Zip -zip "directoryName"
* 解压:java Zip -unzip "fileName.zip"
*/
public class Zip{
private ZipInputStream zipIn; //解压Zip
private ZipOutputStream zipOut; //压缩Zip
private ZipEntry zipEntry;
private static int bufSize; //size of bytes
private byte[] buf;
private int readedBytes;
public Zip(){
this(512);
}
public Zip(int bufSize){
this.bufSize = bufSize;
this.buf = new byte[this.bufSize];
}
//压缩文件夹内的文件
public void doZip(String zipDirectory){//zipDirectoryPath:需要压缩的文件夹名
File file;
File zipDir;
zipDir = new File(zipDirectory);
String zipFileName = zipDir.getName() + ".zip";//压缩后生成的zip文件名
try{
this.zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName)));
handleDir(zipDir , this.zipOut);
this.zipOut.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
//由doZip调用,递归完成目录文件读取
private void handleDir(File dir , ZipOutputStream zipOut)throws IOException{
FileInputStream fileIn;
File[] files;
files = dir.listFiles();
if(files.length == 0){//如果目录为空,则单独创建之.
//ZipEntry的isDirectory()方法中,目录以"/"结尾.
this.zipOut.putNextEntry(new ZipEntry(dir.toString() + "/")); this.zipOut.closeEntry(); } else{//如果目录不为空,则分别处理目录和文件.
for(File fileName : files){
//System.out.println(fileName);
if(fileName.isDirectory()){
handleDir(fileName , this.zipOut);
}
else{
fileIn = new FileInputStream(fileName);
this.zipOut.putNextEntry(new ZipEntry(fileName.toString()));
while((this.readedBytes = fileIn.read(this.buf))>0){
this.zipOut.write(this.buf , 0 , this.readedBytes);
}
this.zipOut.closeEntry();
}
}
}
}
//解压指定zip文件
public void unZip(String unZipfileName){//unZipfileName需要解压的zip文件名
FileOutputStream fileOut;
File file;
try{
this.zipIn = new ZipInputStream (new BufferedInputStream(new FileInputStream(unZipfileName)));
while((this.zipEntry = this.zipIn.getNextEntry()) != null){
file = new File(this.zipEntry.getName());
//System.out.println(file);///
if(this.zipEntry.isDirectory()){
file.mkdirs();
}
else{
//如果指定文件的目录不存在,则创建之.
File parent = file.getParentFile();
if(!parent.exists()){
parent.mkdirs();
}
fileOut = new FileOutputStream(file);
while(( this.readedBytes = this.zipIn.read(this.buf) ) > 0){
fileOut.write(this.buf , 0 , this.readedBytes );
}
fileOut.close();
}
this.zipIn.closeEntry();
}
}catch(IOException ioe){
ioe.printStackTrace();
}
}
//设置缓冲区大小
public void setBufSize(int bufSize){
this.bufSize = bufSize;
}
//测试Zip类
public static void main(String[] args)throws Exception{
if(args.length==2){
String name = args[1];
Zip zip = new Zip();
if(args[0].equals("-zip"))
zip.doZip(name);
else if(args[0].equals("-unzip"))
zip.unZip(name);
} else{ System.out.println("Usage:"); System.out.println("压缩:java Zip -zip http://www.bt285.cn /directoryName"); System.out.println("解压:java Zip -unzip http://www.feng123.com /fileName.zip"); throw new Exception("Arguments error!"); } } } 读书笔记: Java 压缩数据流
Zip和GZIP是最常用的压缩格式,能被多种工具来读写.
压缩类 功能
CheckedInputStream GetCheckSum()为任何InputStream产生校验和(不仅是解压)
CheckedOutputStream GetCheckSum()为任何OutputStream产生校验和(不仅是解压)
DeflaterOutputStream 用于压缩类的基础类
ZipOutputStream 一个DeflaterOutputStream,将数据压缩成Zip文件格式
GZIPOutputStream 一个DeflaterOutputStream,将数据压缩成GZIP文件格式
InflaterInputStream 用于解压类的基础类
ZipInputStream 一个DeflaterInputStream,解压用Zip文件格式保存的数据
GZIPInputStream 一个DeflaterInputStream,解压用GZIP文件格式保存的数据
用GZIP进行简单压缩
GZIP接口非常简单,所以如果只有单个数据流需要压缩(而不是一系列不同的数据),那么它就可能是最适当选择。下面是对单个文件进行压缩的例子:
//: GZIPcompress.java
// Uses Java 1.1 GZIP compression to compress
// a file whose name is passed on the command
// line.
import java.io.*;
import java.util.zip.*;
public class GZIPcompress {
public static void main(String[] args) {
try {
BufferedReader in =
new BufferedReader(
new FileReader(args[0]));
BufferedOutputStream out =
new BufferedOutputStream(
new GZIPOutputStream(
new FileOutputStream("test.gz")));
System.out.println("Writing file");
int c;
while((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
System.out.println("Reading file");
BufferedReader in2 =
new BufferedReader(
new InputStreamReader(
new GZIPInputStream(
new FileInputStream("test.gz"))));
String s;
while((s =e="COLOR: #000000"> in2.readLine()) != null)
System.out.println(s);
} catch(Exception e) {
e.printStackTrace();
}
}
} ///:~
压缩类的用法非常直观--只需将输出流封装到一个GZIPOutputStream或者ZipOutputStream内,并将输入流封装到GZIPInputStream或者ZipInputStream内即可。剩余的全部操作就是标准的IO读写。然而,这是一个很典型的例子,我们不得不混合使用新旧IO流:数据的输入使用Reader类,而GZIPOutputStream的构建器只能接收一个OutputStream对象,不能接收Writer对象。
用Zip进行多文件保存
提供了Zip支持的Java库显得更加全面。利用它可以方便地保存多个文件。甚至有一个独立的类来简化对Zip文件的读操作。这个库采采用的是标准Zip格式,所以能与当前因特网上使用的大量压缩、解压工具很好地协作。下面这个例子采取了与前例相同的形式,但能根据我们需要控制任意数量的命令行参数。除此之外,它展示了如何用Checksum类来计算和校验文件的"校验和"(Checksum)。可选用两种类型的Checksum:Adler32(速度要快一些)和CRC32(慢一些,但更准确)。
//: ZipCompress.java
// Uses Java 1.1 Zip compression to compress
// any number of files whose names are passed
// on the command line.
import java.io.*;
import java.util.*;
import java.util.zip.*;
public class ZipCompress {
public static void main(String[] args) {
try {
FileOutputStream f =
new FileOutputStream("test.zip");
CheckedOutputStream csum =
new CheckedOutputStream(
f, new Adler32());
ZipOutputStream out =
new ZipOutputStream(
new BufferedOutputStream(csum));
out.setComment("A test of Java Zipping");
// Can''t read the above comment, though
for(int i = 0; i resFileList = new ArrayList();
resFileList.add(new File("E:\\1.txt"));
resFileList.add(new File("E:\\2.txt"));
File zipFile = new File("e:\\txxxt.zip");
try {
Zip2Utils.zipFiles(resFileList, zipFile); //测试OK
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static final int BUFF_SIZE = 1024 * 1024; //1M Byte
/**
* 批量压缩文件(夹)
*
* @param resFileList 要压缩的文件(夹)列表
* @param zipFile 生成的压缩文件
* @throws IOException 当压缩过程出错时抛出
*/
public static void zipFiles(Collection resFileList, File zipFile) throws IOException {
ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile), BUFF_SIZE));
for (File resFile : resFileList) {
zipFile(resFile, zipout, "");
}
zipout.close();
}
/**
* 批量压缩文件(夹)
*
* @param resFileList 要压缩的文件(夹)列表
* @param zipFile 生成的压缩文件
* @param comment 压缩文件的注释
* @throws IOException 当压缩过程出错时抛出
*/
public static void zipFiles(Collection resFileList, File zipFile, String comment) throws IOException {
ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile), BUFF_SIZE));
for (File resFile : resFileList) {
zipFile(resFile, zipout, "");
}
zipout.setComment(comment);
zipout.close();
}
/**
* 解压缩一个文件
*
* @param zipFile 压缩文件
* @param folderPath 解压缩的目标目录
* @throws IOException 当压缩过程出错时抛出
*/
public static void upZipFile(File zipFile, String folderPath) throws IOException {
ZipFile zf = new ZipFile(zipFile);
for (Enumeration entries = zf.entries(); entries.hasMoreElements();) {
ZipEntry entry = ((ZipEntry) entries.nextElement());
InputStream in = zf.getInputStream(entry);
OutputStream out = new FileOutputStream(folderPath + File.separator + entry.getName());
byte buffer[] = new byte[BUFF_SIZE];
int realLength;
while ((realLength = in.read(buffer)) > 0) {
out.write(buffer, 0, realLength);
}
in.close();
out.close();
}
}
private static void zipFile(File resFile, ZipOutputStream zipout, String rootpath) throws IOException {
rootpath = rootpath + (rootpath.trim().length() == 0 ? "" : File.separator) + resFile.getName();
if (resFile.isDirectory()) {
File[] fileList = resFile.listFiles();
for (File file : fileList) {
zipFile(file, zipout, rootpath);
}
} else {
byte buffer[] = new byte[BUFF_SIZE];
BufferedInputStream in = new BufferedInputStream(new FileInputStream(resFile), BUFF_SIZE);
zipout.putNextEntry(new ZipEntry(rootpath));
int realLength;
while ((realLength = in.read(buffer)) != -1) {
zipout.write(buffer, 0, realLength);
}
in.close();
zipout.flush();
zipout.closeEntry();
}
}
}
2010年12月13日
特殊流类型:
1,RandomAccessFile
2,压缩与解压:zip/rar,jar,Gzip
(1)zip:zipOutputStream
DataOutputStream
zipEntry
(2)GZip:GZipOutputStream
(3)jar:JarOutputStream
JarEntry
Attribute
3,管道流:PipedInputstream
PipedOutputstream
import java.io.*;
import java.util.zip.*;
/** *//**
*功能:zip压缩、解压
*说明:本程序通过ZipOutputStream和ZipInputStream实现了zip压缩和解压功能.
*问题:由于java.util.zip包并不支持汉字,当zip文件中有名字为中文的文件时
, author by http://www.bt285.cn http://www.5a520.cn
* 就会出现异常:"Exception in thread "main " java.lang.IllegalArgumentException
* at java.util.zip.ZipInputStream.getUTF8String(ZipInpu tStream.java:285)
*解决:
* 方法1、修改import java.util.zip.ZipInputStream和ZipOutputStream.
* java.util.zip只支持UTF-8,Ant里面可以指定编码.
* 方法2、使用Apache Ant里提供的zip工具。
* 不使用java.util.zip的包,把ant.jar放到classpath中.
* 程序中使用import org.apache.tools.zip.*;
*
*仅供编程学习参考.
*
*@author Winty
*@date 2008-8-3
*@Usage:
* 压缩:java Zip -zip "directoryName"
* 解压:java Zip -unzip "fileName.zip"
*/
public class Zip{
private ZipInputStream zipIn; //解压Zip
private ZipOutputStream zipOut; //压缩Zip
private ZipEntry zipEntry;
private static int bufSize; //size of bytes
private byte[] buf;
private int readedBytes;
public Zip(){
this(512);
}
public Zip(int bufSize){
this.bufSize = bufSize;
this.buf = new byte[this.bufSize];
}
//压缩文件夹内的文件
public void doZip(String zipDirectory){//zipDirectoryPath:需要压缩的文件夹名
File file;
File zipDir;
zipDir = new File(zipDirectory);
String zipFileName = zipDir.getName() + ".zip";//压缩后生成的zip文件名
try{
this.zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName)));
handleDir(zipDir , this.zipOut);
this.zipOut.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
//由doZip调用,递归完成目录文件读取
private void handleDir(File dir , ZipOutputStream zipOut)throws IOException{
FileInputStream fileIn;
File[] files;
files = dir.listFiles();
if(files.length == 0){//如果目录为空,则单独创建之.
//ZipEntry的isDirectory()方法中,目录以"/"结尾.
this.zipOut.putNextEntry(new ZipEntry(dir.toString() + "/")); this.zipOut.closeEntry(); } else{//如果目录不为空,则分别处理目录和文件.
for(File fileName : files){
//System.out.println(fileName);
if(fileName.isDirectory()){
handleDir(fileName , this.zipOut);
}
else{
fileIn = new FileInputStream(fileName);
this.zipOut.putNextEntry(new ZipEntry(fileName.toString()));
while((this.readedBytes = fileIn.read(this.buf))>0){
this.zipOut.write(this.buf , 0 , this.readedBytes);
}
this.zipOut.closeEntry();
}
}
}
}
//解压指定zip文件
public void unZip(String unZipfileName){//unZipfileName需要解压的zip文件名
FileOutputStream fileOut;
File file;
try{
this.zipIn = new ZipInputStream (new BufferedInputStream(new FileInputStream(unZipfileName)));
while((this.zipEntry = this.zipIn.getNextEntry()) != null){
file = new File(this.zipEntry.getName());
//System.out.println(file);///
if(this.zipEntry.isDirectory()){
file.mkdirs();
}
else{
//如果指定文件的目录不存在,则创建之.
File parent = file.getParentFile();
if(!parent.exists()){
parent.mkdirs();
}
fileOut = new FileOutputStream(file);
while(( this.readedBytes = this.zipIn.read(this.buf) ) > 0){
fileOut.write(this.buf , 0 , this.readedBytes );
}
fileOut.close();
}
this.zipIn.closeEntry();
}
}catch(IOException ioe){
ioe.printStackTrace();
}
}
//设置缓冲区大小
public void setBufSize(int bufSize){
this.bufSize = bufSize;
}
//测试Zip类
public static void main(String[] args)throws Exception{
if(args.length==2){
String name = args[1];
Zip zip = new Zip();
if(args[0].equals("-zip"))
zip.doZip(name);
else if(args[0].equals("-unzip"))
zip.unZip(name);
} else{ System.out.println("Usage:"); System.out.println("压缩:java Zip -zip http://www.bt285.cn /directoryName"); System.out.println("解压:java Zip -unzip http://www.feng123.com /fileName.zip"); throw new Exception("Arguments error!"); } } } 读书笔记: Java 压缩数据流
Zip和GZIP是最常用的压缩格式,能被多种工具来读写.
压缩类 功能
CheckedInputStream GetCheckSum()为任何InputStream产生校验和(不仅是解压)
CheckedOutputStream GetCheckSum()为任何OutputStream产生校验和(不仅是解压)
DeflaterOutputStream 用于压缩类的基础类
ZipOutputStream 一个DeflaterOutputStream,将数据压缩成Zip文件格式
GZIPOutputStream 一个DeflaterOutputStream,将数据压缩成GZIP文件格式
InflaterInputStream 用于解压类的基础类
ZipInputStream 一个DeflaterInputStream,解压用Zip文件格式保存的数据
GZIPInputStream 一个DeflaterInputStream,解压用GZIP文件格式保存的数据
用GZIP进行简单压缩
GZIP接口非常简单,所以如果只有单个数据流需要压缩(而不是一系列不同的数据),那么它就可能是最适当选择。下面是对单个文件进行压缩的例子:
//: GZIPcompress.java
// Uses Java 1.1 GZIP compression to compress
// a file whose name is passed on the command
// line.
import java.io.*;
import java.util.zip.*;
public class GZIPcompress {
public static void main(String[] args) {
try {
BufferedReader in =
new BufferedReader(
new FileReader(args[0]));
BufferedOutputStream out =
new BufferedOutputStream(
new GZIPOutputStream(
new FileOutputStream("test.gz")));
System.out.println("Writing file");
int c;
while((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
System.out.println("Reading file");
BufferedReader in2 =
new BufferedReader(
new InputStreamReader(
new GZIPInputStream(
new FileInputStream("test.gz"))));
String s;
while((s =e="COLOR: #000000"> in2.readLine()) != null)
System.out.println(s);
} catch(Exception e) {
e.printStackTrace();
}
}
} ///:~
压缩类的用法非常直观--只需将输出流封装到一个GZIPOutputStream或者ZipOutputStream内,并将输入流封装到GZIPInputStream或者ZipInputStream内即可。剩余的全部操作就是标准的IO读写。然而,这是一个很典型的例子,我们不得不混合使用新旧IO流:数据的输入使用Reader类,而GZIPOutputStream的构建器只能接收一个OutputStream对象,不能接收Writer对象。
用Zip进行多文件保存
提供了Zip支持的Java库显得更加全面。利用它可以方便地保存多个文件。甚至有一个独立的类来简化对Zip文件的读操作。这个库采采用的是标准Zip格式,所以能与当前因特网上使用的大量压缩、解压工具很好地协作。下面这个例子采取了与前例相同的形式,但能根据我们需要控制任意数量的命令行参数。除此之外,它展示了如何用Checksum类来计算和校验文件的"校验和"(Checksum)。可选用两种类型的Checksum:Adler32(速度要快一些)和CRC32(慢一些,但更准确)。
//: ZipCompress.java
// Uses Java 1.1 Zip compression to compress
// any number of files whose names are passed
// on the command line.
import java.io.*;
import java.util.*;
import java.util.zip.*;
public class ZipCompress {
public static void main(String[] args) {
try {
FileOutputStream f =
new FileOutputStream("test.zip");
CheckedOutputStream csum =
new CheckedOutputStream(
f, new Adler32());
ZipOutputStream out =
new ZipOutputStream(
new BufferedOutputStream(csum));
out.setComment("A test of Java Zipping");
// Can''t read the above comment, though
for(int i = 0; i resFileList = new ArrayList();
resFileList.add(new File("E:\\1.txt"));
resFileList.add(new File("E:\\2.txt"));
File zipFile = new File("e:\\txxxt.zip");
try {
Zip2Utils.zipFiles(resFileList, zipFile); //测试OK
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static final int BUFF_SIZE = 1024 * 1024; //1M Byte
/**
* 批量压缩文件(夹)
*
* @param resFileList 要压缩的文件(夹)列表
* @param zipFile 生成的压缩文件
* @throws IOException 当压缩过程出错时抛出
*/
public static void zipFiles(Collection resFileList, File zipFile) throws IOException {
ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile), BUFF_SIZE));
for (File resFile : resFileList) {
zipFile(resFile, zipout, "");
}
zipout.close();
}
/**
* 批量压缩文件(夹)
*
* @param resFileList 要压缩的文件(夹)列表
* @param zipFile 生成的压缩文件
* @param comment 压缩文件的注释
* @throws IOException 当压缩过程出错时抛出
*/
public static void zipFiles(Collection resFileList, File zipFile, String comment) throws IOException {
ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile), BUFF_SIZE));
for (File resFile : resFileList) {
zipFile(resFile, zipout, "");
}
zipout.setComment(comment);
zipout.close();
}
/**
* 解压缩一个文件
*
* @param zipFile 压缩文件
* @param folderPath 解压缩的目标目录
* @throws IOException 当压缩过程出错时抛出
*/
public static void upZipFile(File zipFile, String folderPath) throws IOException {
ZipFile zf = new ZipFile(zipFile);
for (Enumeration entries = zf.entries(); entries.hasMoreElements();) {
ZipEntry entry = ((ZipEntry) entries.nextElement());
InputStream in = zf.getInputStream(entry);
OutputStream out = new FileOutputStream(folderPath + File.separator + entry.getName());
byte buffer[] = new byte[BUFF_SIZE];
int realLength;
while ((realLength = in.read(buffer)) > 0) {
out.write(buffer, 0, realLength);
}
in.close();
out.close();
}
}
private static void zipFile(File resFile, ZipOutputStream zipout, String rootpath) throws IOException {
rootpath = rootpath + (rootpath.trim().length() == 0 ? "" : File.separator) + resFile.getName();
if (resFile.isDirectory()) {
File[] fileList = resFile.listFiles();
for (File file : fileList) {
zipFile(file, zipout, rootpath);
}
} else {
byte buffer[] = new byte[BUFF_SIZE];
BufferedInputStream in = new BufferedInputStream(new FileInputStream(resFile), BUFF_SIZE);
zipout.putNextEntry(new ZipEntry(rootpath));
int realLength;
while ((realLength = in.read(buffer)) != -1) {
zipout.write(buffer, 0, realLength);
}
in.close();
zipout.flush();
zipout.closeEntry();
}
}
}