java创建zip文件的代码如下如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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; import java.util.zip.zipoutputstream; public class zipdemo { public static void main(string[] args) throws ioexception { file file = new file( "test.zip" ); if (!file.exists()) file.createnewfile(); string string= "test zip!" ; byte [] buffer =string.getbytes(); fileoutputstream foutputstream = new fileoutputstream(file); zipoutputstream zoutput = new zipoutputstream(foutputstream); zipentry zentry = new zipentry( "test.txt" ); zoutput.putnextentry(zentry); zoutput.write(buffer); zoutput.closeentry(); zoutput.close(); } } |
补充:下面看下java中创建zip文件,并向zip文件中写入并读取条目和数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
package file; 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; import java.util.zip.zipoutputstream; public class zipdemo { public static void main(string[] args) throws ioexception { // todo auto-generated method stub file file = new file( "test.zip" ); if (!file.exists()) file.createnewfile(); string string= "my name is ysd!" ; byte [] buffer =string.getbytes(); byte [] bufferinput = new byte [ 4096 ]; fileoutputstream foutputstream = new fileoutputstream(file); zipoutputstream zoutput = new zipoutputstream(foutputstream); zipentry zentry = new zipentry( "one.txt" ); zoutput.putnextentry(zentry); zoutput.write(buffer); zoutput.closeentry(); zoutput.close(); zipinputstream zinputstream = new zipinputstream( new fileinputstream(file)); zipentry zipentry = null ; while ((zipentry=zinputstream.getnextentry()) != null ) { system.out.println(zipentry.getname()); zinputstream.read(bufferinput); system.out.println( new string(bufferinput)); zinputstream.closeentry(); } zinputstream.close(); } } |
总结
以上所述是小编给大家介绍的java中创建zip文件的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:https://blog.csdn.net/sgrrmswtvt/article/details/80648133