写一段java代码,可以将本地文件上传到linux服务器
时间: 2023-06-14 10:08:08 浏览: 155
以下是一个简单的Java代码示例,可以将本地文件上传到Linux服务器上:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class FileUploader {
public static void main(String[] args) {
String localFilePath = "/path/to/local/file";
String remoteFilePath = "/path/to/remote/file";
String remoteHost = "remote_host";
String remoteUser = "remote_user";
String remotePassword = "remote_password";
int remotePort = 22;
try {
uploadFile(localFilePath, remoteFilePath, remoteHost, remoteUser, remotePassword, remotePort);
System.out.println("File uploaded successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void uploadFile(String localFilePath, String remoteFilePath, String remoteHost, String remoteUser, String remotePassword, int remotePort) throws Exception {
JSch jsch = new JSch();
Session session = jsch.getSession(remoteUser, remoteHost, remotePort);
session.setPassword(remotePassword);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
File localFile = new File(localFilePath);
InputStream inputStream = new FileInputStream(localFile);
sftpChannel.put(inputStream, remoteFilePath);
sftpChannel.exit();
session.disconnect();
}
}
```
需要使用到JSch库,可以在Maven中添加以下依赖:
```xml
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
```
其中,`localFilePath`表示本地文件的路径,`remoteFilePath`表示远程服务器上保存文件的路径,`remoteHost`表示远程服务器的IP地址,`remoteUser`和`remotePassword`表示登录远程服务器的用户名和密码,`remotePort`表示远程服务器的SSH端口号。
阅读全文