一个zip文件解压后是一个bin文件,用java如何将这个zip文件里的数据存到指定名字的txt文件中
时间: 2023-05-28 07:04:16 浏览: 93
您可以按照以下步骤使用Java解压缩并将zip文件中的数据存储到指定名称的txt文件中:
1. 使用Java的ZipInputStream类来解压缩zip文件。这可以通过创建一个新的ZipInputStream对象并将其连接到zip文件的InputStream来完成。
2. 将ZipInputStream中的数据读取到一个字节数组中。这可以通过创建一个字节数组缓冲区并使用ZipInputStream的read方法来完成。
3. 将字节数组中的数据写入txt文件中。这可以通过使用Java的FileOutputStream类来创建一个新的txt文件,并使用其write方法将字节数组中的数据写入该文件中。
以下是示例代码:
```java
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipAndWriteTxtFile {
public static void main(String[] args) throws IOException {
String zipFilePath = "path/to/zip/file.zip";
String txtFilePath = "path/to/txt/file.txt";
// Create a new ZipInputStream object connected to the zip file input stream
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath));
// Loop through each entry in the zip file
ZipEntry zipEntry = zipInputStream.getNextEntry();
while (zipEntry != null) {
// If the entry is not a directory
if (!zipEntry.isDirectory()) {
// Create a new byte array to hold the data for this entry
byte[] data = new byte[(int) zipEntry.getSize()];
// Read the data from the ZipInputStream into the byte array
zipInputStream.read(data);
// Write the data to the txt file
FileOutputStream fileOutputStream = new FileOutputStream(txtFilePath);
fileOutputStream.write(data);
fileOutputStream.close();
// Close the ZipEntry and move on to the next one
zipInputStream.closeEntry();
zipEntry = zipInputStream.getNextEntry();
}
}
// Close the ZipInputStream
zipInputStream.close();
}
}
```
请注意,此代码仅适用于zip文件中只有一个条目的情况。如果zip文件中有多个条目,则需要在循环中处理每个条目并将数据写入不同的txt文件中。