打卡~~
Topic source酱紫行不行啊廖老师?
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/**
* @authur zhangqizky
* @apiNote 操作zip:ZipInputStream和JarInputStream
*/
public class MyZip
{
public static void main(String[]args)throws Exception
{
/**
* @从zip文件中读取
*/
try(ZipInputStream zip = new ZipInputStream(new FileInputStream("day02.zip")))
{
ZipEntry entry = null;
while((entry = zip.getNextEntry()) != null)
{
String name = entry.getName();
if(!entry.isDirectory())
{
int n;
while((n=zip.read())!=-1)
{
System.out.println(n);
}
}
}
}
/**
* @写入Zip文件
*/
try(ZipOutputStream zip = new ZipOutputStream(new FileOutputStream("out.zip")))
{
File[]files = {new File("MyFile.java"),new File("MyFilter.java")};
for (File f :files)
{
zip.putNextEntry(new ZipEntry(f.getName()));
zip.write(getFileDataAsBytes(f));
zip.closeEntry();
}
}
}
public static byte[] getFileDataAsBytes(File f)
{
byte[] data = new byte[(int)f.length()];
try(InputStream is =new FileInputStream(f))
{
int n;
while((n=is.read(data))!=-1)
{
System.out.println("read"+n+"bytes");
}
}catch(IOException e)
{
e.printStackTrace();
}
return data;
}
}
准确地说:
byte[] data = new byte[(int)f.length()];
try(InputStream is =new FileInputStream(f))
你这两行代码之间,有可能文件会被其他程序修改,导致实际读取的字节与文件长度不一致
用ByteArrayOutputStream,那个就是用来在内存中开辟缓存的。
byte[] data = new byte[(int) f.length()];try (//InputStream inputStream = new FileInputStream(f);InputStream inputStream = new ByteArrayInputStream(data)) {
public static byte[] getFileDataAsBytes(File f) throws IOException {
byte[] data = new byte[1024];
//ByteArrayOutputStream bin; System.out.println(f.length());
try(FileInputStream fi = new FileInputStream(f)){
try(ByteArrayOutputStream bin = new ByteArrayOutputStream(1024)){
int n;
while ((n = fi.read()) != -1){
bin.write(n);
}
return bin.toByteArray();
}
}
}
不过这个byteoutputsteam的参数不知道是啥意思,是会自动扩容吗?我试了用大文件也可以正常运行压缩
public ByteArrayOutputStream(int size) { if (size < 0) { throw new IllegalArgumentException("Negative initial size: " + size); } buf = new byte[size];}
- 1
用户5527594890
找了半天,发现getFileDataAsBytes()这个函数java标准库中并没有,自己写了一个~