使用java实现windows与unix文件互传
时间: 2024-02-09 19:12:59 浏览: 26
您好!实现Windows与Unix文件互传,可以使用Java中的SFTP(SSH File Transfer Protocol)协议。SFTP是一种安全的文件传输协议,可以在不安全的网络环境下进行文件传输。
以下是一个使用JSch库实现SFTP文件上传和下载的示例代码:
```
import com.jcraft.jsch.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class SftpDemo {
public static void main(String[] args) throws Exception {
String host = "your-hostname";
String username = "your-username";
String password = "your-password";
int port = 22;
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
// upload file from Windows to Unix
String localFilePath = "path/to/local/file";
String remoteFilePath = "path/to/remote/file";
FileInputStream fis = new FileInputStream(new File(localFilePath));
channel.put(fis, remoteFilePath);
fis.close();
// download file from Unix to Windows
String localFilePath2 = "path/to/local/file2";
String remoteFilePath2 = "path/to/remote/file2";
FileOutputStream fos = new FileOutputStream(new File(localFilePath2));
channel.get(remoteFilePath2, fos);
fos.close();
channel.disconnect();
session.disconnect();
}
}
```
在上面的示例代码中,我们使用JSch库创建了一个SFTP会话,并通过Session和Channel实例进行文件上传和下载操作。需要注意的是,您需要将`your-hostname`,`your-username`和`your-password`替换为实际的主机名、用户名和密码。
希望这可以帮到您!