Java /C# 实现文件压缩
时间: 2023-08-15 20:09:56 浏览: 156
C#实现文件压缩
Java实现文件压缩可以使用Java内置的ZipOutputStream类。下面是一个示例代码:
```java
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class FileCompressor {
public static void main(String[] args) throws Exception {
String sourceFile = "source.txt";
String compressedFile = "compressed.zip";
compress(sourceFile, compressedFile);
}
private static void compress(String sourceFile, String compressedFile) throws Exception {
FileOutputStream fos = new FileOutputStream(compressedFile);
ZipOutputStream zos = new ZipOutputStream(fos);
File file = new File(sourceFile);
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(file.getName());
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
fis.close();
zos.close();
fos.close();
}
}
```
C#实现文件压缩可以使用System.IO.Compression.ZipArchive类。下面是一个示例代码:
```csharp
using System.IO;
using System.IO.Compression;
class Program {
static void Main(string[] args) {
string sourceFile = "source.txt";
string compressedFile = "compressed.zip";
Compress(sourceFile, compressedFile);
}
private static void Compress(string sourceFile, string compressedFile) {
using (FileStream fs = new FileStream(compressedFile, FileMode.Create)) {
using (ZipArchive zipArchive = new ZipArchive(fs, ZipArchiveMode.Create)) {
zipArchive.CreateEntryFromFile(sourceFile, Path.GetFileName(sourceFile));
}
}
}
}
```
阅读全文