ftp上传文件到服务器java代码
时间: 2023-08-30 07:05:17 浏览: 183
好的,关于这个问题,以下是一个简单的示例代码:
```
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class FTPUploader {
public static void main(String[] args) {
String server = "yourFTPserver.com";
int port = 21;
String username = "yourUsername";
String password = "yourPassword";
String filePath = "/path/to/your/file.txt";
String remoteDirPath = "/remote/directory/path/";
try {
Socket socket = new Socket(server, port);
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
login(username, password, inputStream, outputStream);
sendCommand("CWD " + remoteDirPath, inputStream, outputStream);
sendCommand("TYPE I", inputStream, outputStream);
File file = new File(filePath);
FileInputStream fileInputStream = new FileInputStream(file);
sendCommand("STOR " + file.getName(), inputStream, outputStream);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
fileInputStream.close();
outputStream.close();
inputStream.close();
socket.close();
System.out.println("File transfer complete!");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void login(String username, String password, InputStream inputStream, OutputStream outputStream) throws IOException {
sendCommand("USER " + username, inputStream, outputStream);
sendCommand("PASS " + password, inputStream, outputStream);
}
private static void sendCommand(String command, InputStream inputStream, OutputStream outputStream) throws IOException {
outputStream.write((command + "\r\n").getBytes());
String response = readResponse(inputStream);
System.out.println("> " + command);
System.out.println("< " + response);
}
private static String readResponse(InputStream inputStream) throws IOException {
byte[] buffer = new byte[4096];
int bytesRead = inputStream.read(buffer);
return new String(buffer, 0, bytesRead);
}
}
```
这是一个基本的FTP上传文件的Java代码,需要根据你的具体情况进行修改。这段代码使用Socket连接FTP服务器,登录验证后进入指定的远程目录,将本地文件上传到服务器。
阅读全文