如何用java创建一个加密的压缩包
答案:2 悬赏:10 手机版
解决时间 2021-03-14 21:48
- 提问者网友:疯子也有疯子的情调
- 2021-03-14 17:04
如何用java创建一个加密的压缩包
最佳答案
- 五星知识达人网友:几近狂妄
- 2021-03-14 17:22
下面的示例代码演示如何创建zip压缩包。
首先需要由需要压缩的文件创建一个InputStream对象,然后读取文件内容写入到ZipOutputStream中。
ZipOutputStream类接受FileOutputStream作为参数。创建号ZipOutputStream对象后需要创建一个zip entry,然后写入。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Main {
public void createZipFile() {
try {
String inputFileName = "test.txt";
String zipFileName = "compressed.zip";
//Create input and output streams
FileInputStream inStream = new FileInputStream(inputFileName);
ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipFileName));
// Add a zip entry to the output stream
outStream.putNextEntry(new ZipEntry(inputFileName));
byte[] buffer = new byte[1024];
int bytesRead;
//Each chunk of data read from the input stream
//is written to the output stream
while ((bytesRead = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, bytesRead);
}
//Close zip entry and file streams
outStream.closeEntry();
outStream.close();
inStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
new Main().createZipFile();
}
首先需要由需要压缩的文件创建一个InputStream对象,然后读取文件内容写入到ZipOutputStream中。
ZipOutputStream类接受FileOutputStream作为参数。创建号ZipOutputStream对象后需要创建一个zip entry,然后写入。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Main {
public void createZipFile() {
try {
String inputFileName = "test.txt";
String zipFileName = "compressed.zip";
//Create input and output streams
FileInputStream inStream = new FileInputStream(inputFileName);
ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipFileName));
// Add a zip entry to the output stream
outStream.putNextEntry(new ZipEntry(inputFileName));
byte[] buffer = new byte[1024];
int bytesRead;
//Each chunk of data read from the input stream
//is written to the output stream
while ((bytesRead = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, bytesRead);
}
//Close zip entry and file streams
outStream.closeEntry();
outStream.close();
inStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
new Main().createZipFile();
}
全部回答
- 1楼网友:独行浪子会拥风
- 2021-03-14 19:01
你说的是jar包吧?jar包要想在eclipse中打开,首先要引入这个包,然后才能看。
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯