java代码传输zip
时间: 2023-07-29 13:10:46 浏览: 36
以下是一个简单的 Java 代码示例,它将一个文件夹压缩为一个zip文件,并将该zip文件传输到另一个计算机:
```java
import java.io.*;
import java.net.*;
public class ZipTransfer {
public static void main(String[] args) {
String folderPath = "/path/to/folder"; // 需要压缩的文件夹路径
String zipPath = "/path/to/zipfile.zip"; // 压缩后的zip文件路径
String remoteHost = "192.168.1.100"; // 目标计算机的IP地址
int remotePort = 8080; // 目标计算机的接收端口号
// 压缩文件夹
try {
FileOutputStream fos = new FileOutputStream(zipPath);
ZipOutputStream zos = new ZipOutputStream(fos);
zipFolder(zos, folderPath, folderPath);
zos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
// 传输zip文件
try {
Socket socket = new Socket(remoteHost, remotePort);
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream(zipPath);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
fis.close();
os.flush();
os.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 压缩文件夹的递归方法
private static void zipFolder(ZipOutputStream zos, String folderPath, String basePath) throws IOException {
File folder = new File(folderPath);
if (folder.isDirectory()) {
File[] files = folder.listFiles();
for (File file : files) {
String filePath = file.getAbsolutePath();
String entryName = filePath.substring(basePath.length() + 1);
if (file.isDirectory()) {
zos.putNextEntry(new ZipEntry(entryName + "/"));
zipFolder(zos, filePath, basePath);
} else {
zos.putNextEntry(new ZipEntry(entryName));
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
zos.write(buffer, 0, len);
}
fis.close();
}
zos.closeEntry();
}
}
}
}
```
在这个示例中,我们使用`java.util.zip.ZipOutputStream`类将文件夹压缩为一个zip文件,并使用`java.net.Socket`类将该zip文件传输到另一个计算机。需要注意的是,传输文件时需要注意数据的编码方式,以及传输时的数据大小和传输速度等问题。