首页系统zipentry(什么是ZipEntry)

zipentry(什么是ZipEntry)

编程之家2024-06-04112次浏览

一、java中的ZipEntry是什么意思

ZipEntry类是java.util.zip包下的一个类,

zipentry(什么是ZipEntry)

ZipEntry类用于表示 ZIP文件条目。

利用这个类压缩和解压zip文件

具体压缩的例子如下:

importjava.io.File;

importjava.io.FileInputStream;

importjava.io.FileNotFoundException;

zipentry(什么是ZipEntry)

importjava.io.FileOutputStream;

importjava.io.IOException;

importjava.util.zip.ZipEntry;

importjava.util.zip.ZipOutputStream;

/**

*压缩程序

zipentry(什么是ZipEntry)

*@authoryoung

*

*/

publicclassSingleFileZip{

publicstaticvoidmain(String[]args){

Filefile=newFile("e:/test.txt");

FileInputStreamfis=null;

ZipOutputStreamzos=null;

try{

fis=newFileInputStream(file);

zos=newZipOutputStream(newFileOutputStream("e:/my.zip"));

//创建压缩文件中的条目

ZipEntryentry=newZipEntry(file.getName());

//将创建好的条目加入到压缩文件中

zos.putNextEntry(entry);

//写入当前条目所对应的具体内容

byte[]buff=newbyte[1024];

intlen=0;

while((len=fis.read(buff))!=-1){

zos.write(buff,0,len);

}

}catch(FileNotFoundExceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}catch(IOExceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}finally{

try{

fis.close();

zos.close();

}catch(IOExceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}

}

}

}

解压例子如下:

importjava.io.FileInputStream;

importjava.io.FileNotFoundException;

importjava.io.FileOutputStream;

importjava.io.IOException;

importjava.io.InputStream;

importjava.util.zip.ZipEntry;

importjava.util.zip.ZipFile;

importjava.util.zip.ZipInputStream;

/**

*解压程序

*@authoryoung

*

*/

publicclassSingleFileUnZip{

publicstaticvoidmain(String[]args){

FileOutputStreamfos=null;

ZipInputStreamzis=null;

InputStreamis=null;

try{

ZipFilezf=newZipFile("e:/my.zip");

zis=newZipInputStream(newFileInputStream("e:/my.zip"));

fos=newFileOutputStream("e:/unzip.txt");

//从压缩文件中获取一个条目

ZipEntryentry=zis.getNextEntry();

//获得该条目对象的数据流

is=zf.getInputStream(entry);

byte[]buff=newbyte[1024];

intlen=0;

while((len=is.read(buff))!=-1){

fos.write(buff,0,len);

}

}catch(FileNotFoundExceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}catch(IOExceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}finally{

try{

is.close();

zis.close();

fos.close();

}catch(IOExceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}

}

}

}

二、UltraEdit-32显示色彩问题

视图->查看方式,看看默认选的什么,里面有没有java项,有的话选上。没有的话,打开高级->配置->编辑器显示->语法高亮->词语列表的完整路径,把它打开。一般默认是WORDFILE.UEW文件,查找一下,看看有没有java的高亮代码,如果没有的话,把下面这段代码复制过去:

----------------------------------------------线下的

/L4"Java" JAVA_LANG Line Comment=// Block Comment On=/* Block Comment Off=*/ Escape Char=\ File Extensions= JAV JAVA

/Delimiters=~!@%^&*()-+=|\/{}[]:;"'<>,.?

/Function String="%[ ^t]++[ps][a-z]+ [a-z0-9]+ ^(*(*)^)*{$"

/Function String 1="%[ ^t]++[ps][a-z]+ [a-z0-9]+ ^(*(*)^)[ ^t]++$"

/Member String="^([A-Za-z0-9_:.]+^)[ ^t*&]+$S[ ^t]++[(=);,]"

/Variable String="^([A-Za-z0-9_:.]+^)[ ^t*&]+$S[ ^t]++[(=);,]"

/Indent Strings="{"

/Unindent Strings="}"

/Open Brace Strings="{""(""[""<"

/Close Brace Strings="}"")""]"">"

/Open Fold Strings="{"

/Close Fold Strings="}"

/C1"Keywords" STYLE_KEYWORD

abstract

boolean break byte

case catch char class continue

default do double

else extends

false final finally float for

if implements import instanceof int interface

length long

native new null

package private protected public

return

short static super switch synchronized

this threadsafe throw throws transient true try

void

while

/C2"Classes" STYLE_FUNCTION

AWTError AWTEvent AWTEventMulticaster AWTException AbstractMethodError AccessException Acl AclEntry

AclNotFoundException ActionEvent ActionListener Adjustable AdjustmentEvent AdjustmentListener Adler32

AlreadyBoundException Applet AppletContext AppletStub AreaAveragingScaleFilter ArithmeticException Array

ArrayIndexOutOfBoundsException ArrayStoreException AudioClip

BeanDescriptor BeanInfo Beans BigDecimal BigInteger BindException BitSet Boolean BorderLayout

BreakIterator BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter Button ButtonPeer

Byte ByteArrayInputStream ByteArrayOutputStream

CRC32 Calendar CallableStatement Canvas CanvasPeer CardLayout Certificate CharArrayReader CharArrayWriter

CharConversionException Character CharacterIterator Checkbox CheckboxGroup CheckboxMenuItem

CheckboxMenuItemPeer CheckboxPeer CheckedInputStream CheckedOutputStream Checksum Choice ChoiceFormat

ChoicePeer Class ClassCastException ClassCircularityError ClassFormatError ClassLoader

ClassNotFoundException Clipboard ClipboardOwner CloneNotSupportedException Cloneable

CollationElementIterator CollationKey Collator Color ColorModel Compiler Component ComponentAdapter

ComponentEvent ComponentListener ComponentPeer ConnectException ConnectIOException Connection Constructor

Container ContainerAdapter ContainerEvent ContainerListener ContainerPeer ContentHandler

ContentHandlerFactory CropImageFilter Cursor Customizer

DGC DSAKey DSAKeyPairGenerator DSAParams DSAPrivateKey DSAPublicKey DataFlavor DataFormatException

DataInput DataInputStream DataOutput DataOutputStream DataTruncation DatabaseMetaData DatagramPacket

DatagramSocket DatagramSocketImpl Date DateFormat DateFormatSymbols DecimalFormat DecimalFormatSymbols

Deflater DeflaterOutputStream Dialog DialogPeer Dictionary DigestException DigestInputStream

DigestOutputStream Dimension DirectColorModel Double Driver DriverManager DriverPropertyInfo

EOFException EmptyStackException Enumeration Error Event EventListener EventObject EventQueue

EventSetDescriptor Exception ExceptionInInitializerError ExportException

FeatureDescriptor Field FieldPosition File FileDescriptor FileDialog FileDialogPeer FileInputStream

FileNameMap FileNotFoundException FileOutputStream FileReader FileWriter FilenameFilter FilterInputStream

FilterOutputStream FilterReader FilterWriter FilteredImageSource Float FlowLayout FocusAdapter FocusEvent

FocusListener Font FontMetrics FontPeer Format Frame FramePeer

GZIPInputStream GZIPOutputStream Graphics GregorianCalendar GridBagConstraints GridBagLayout GridLayout

Group

Hashtable HttpURLConnection

IOException Identity IdentityScope IllegalAccessError IllegalAccessException IllegalArgumentException

IllegalComponentStateException IllegalMonitorStateException IllegalStateException

IllegalThreadStateException Image ImageConsumer ImageFilter ImageObserver ImageProducer

IncompatibleClassChangeError IndexColorModel IndexOutOfBoundsException IndexedPropertyDescriptor

InetAddress Inflater InflaterInputStream InputEvent InputStream InputStreamReader Insets

InstantiationError InstantiationException Integer InternalError InterruptedException

InterruptedIOException IntrospectionException Introspector InvalidClassException InvalidKeyException

InvalidObjectException InvalidParameterException InvocationTargetException ItemEvent ItemListener

ItemSelectable

Key KeyAdapter KeyEvent KeyException KeyListener KeyManagementException KeyPair KeyPairGenerator

Label LabelPeer LastOwnerException LayoutManager LayoutManager2 Lease LightweightPeer

LineNumberInputStream LineNumberReader LinkageError List ListPeer ListResourceBundle LoaderHandler Locale

LocateRegistry LogStream Long

MalformedURLException MarshalException Math MediaTracker Member MemoryImageSource Menu MenuBar MenuBarPeer

MenuComponent MenuComponentPeer MenuContainer MenuItem MenuItemPeer MenuPeer MenuShortcut MessageDigest

MessageFormat Method MethodDescriptor MissingResourceException Modifier MouseAdapter MouseEvent

MouseListener MouseMotionAdapter MouseMotionListener MulticastSocket

Naming NegativeArraySizeException NoClassDefFoundError NoRouteToHostException NoSuchAlgorithmException

NoSuchElementException NoSuchFieldError NoSuchFieldException NoSuchMethodError NoSuchMethodException

NoSuchObjectException NoSuchProviderException NotActiveException NotBoundException NotOwnerException

NotSerializableException NullPointerException Number NumberFormat NumberFormatException

ObjID Object ObjectInput ObjectInputStream ObjectInputValidation ObjectOutput ObjectOutputStream

ObjectStreamClass ObjectStreamException Observable Observer Operation OptionalDataException

OutOfMemoryError OutputStream OutputStreamWriter Owner

PaintEvent Panel PanelPeer ParameterDescriptor ParseException ParsePosition Permission PipedInputStream

PipedOutputStream PipedReader PipedWriter PixelGrabber Point Polygon PopupMenu PopupMenuPeer

PreparedStatement Principal PrintGraphics PrintJob PrintStream PrintWriter PrivateKey Process Properties

PropertyChangeEvent PropertyChangeListener PropertyChangeSupport PropertyDescriptor PropertyEditor

PropertyEditorManager PropertyEditorSupport PropertyResourceBundle PropertyVetoException ProtocolException

Provider ProviderException PublicKey PushbackInputStream PushbackReader

RGBImageFilter RMIClassLoader RMIFailureHandler RMISecurityException RMISecurityManager RMISocketFactory

Random RandomAccessFile Reader Rectangle Registry RegistryHandler Remote RemoteCall RemoteException

RemoteObject RemoteRef RemoteServer RemoteStub ReplicateScaleFilter ResourceBundle ResultSet

ResultSetMetaData RuleBasedCollator Runnable Runtime RuntimeException

SQLException SQLWarning ScrollPane ScrollPanePeer Scrollbar ScrollbarPeer SecureRandom Security

SecurityException SecurityManager SequenceInputStream Serializable ServerCloneException ServerError

ServerException ServerNotActiveException ServerRef ServerRuntimeException ServerSocket Shape Short

Signature SignatureException Signer SimpleBeanInfo SimpleDateFormat SimpleTimeZone Skeleton

SkeletonMismatchException SkeletonNotFoundException Socket SocketException SocketImpl SocketImplFactory

SocketSecurityException Stack StackOverflowError Statement StreamCorruptedException StreamTokenizer String

StringBuffer StringBufferInputStream StringCharacterIterator StringIndexOutOfBoundsException StringReader

StringSelection StringTokenizer StringWriter StubNotFoundException SyncFailedException System SystemColor

TextArea TextAreaPeer TextComponent TextComponentPeer TextEvent TextField TextFieldPeer TextListener

Thread ThreadDeath ThreadGroup Throwable Time TimeZone Timestamp TooManyListenersException Toolkit

Transferable Types

UID URL URLConnection URLEncoder URLStreamHandler URLStreamHandlerFactory UTFDataFormatException

UnexpectedException UnicastRemoteObject UnknownError UnknownHostException UnknownServiceException

UnmarshalException Unreferenced UnsatisfiedLinkError UnsupportedEncodingException

UnsupportedFlavorException

VMID Vector VerifyError VetoableChangeListener VetoableChangeSupport VirtualMachineError Visibility Void

Window WindowAdapter WindowEvent WindowListener WindowPeer WriteAbortedException Writer

ZipEntry ZipException ZipFile ZipInputStream ZipOutputStream

/C3"Operators" STYLE_OPERATOR

!

%

&

*

+

-

///

<

=

>

^

|

~

------------------------------------------------到线上结束

其中第一行L4是行号,不要与文件中的重复就可以了。

三、JDK ZipEntry压缩中文文件名乱码解决

项目中碰到问题.jdk zipEntry压缩中文文件名乱码

上网查了下,有两种方法,一种修改jdk ZipInputStream及ZipOutputStream的源文件,比较麻烦,不建议此项.

第二种就是拿来主义,因为开源项目 Ant里已经有现成的实现.把ant.jar加入到工程下的lib目录即可.

如果仅用到压缩,就加入ant.jar就导致引入了一些不必要的文件,所以我找到Ant1.8的源码,然后只把需要的那一部分编译打包成了一个jar文件,供大家使用

首先引入

Java代码

import org.apache.tools.zip.ZipEntry;

import org.apache.tools.zip.ZipOutputStream;

关键示例代码如下:

Java代码

zos= new ZipOutputStream(new FileOutputStream(zipname));

FileInputStream fis= new FileInputStream(file);

ZipEntry ze= new ZipEntry(file.getName());

ze.setSize(file.length());

ze.setTime(file.lastModified());

zos.putNextEntry(ze); zos.setEncoding("gbk");

文件夹乱码(文件夹乱码是什么原因呢)等价无穷小?无穷小替换18个公式