编写个文件上传的Java程序
时间: 2023-07-24 20:00:29 浏览: 46
好的,下面是一个简单的文件上传的 Java 程序,可以供您参考:
```java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
public class FileUploader {
private String host; // 服务器IP地址
private int port; // 服务器端口号
public FileUploader(String host, int port) {
this.host = host;
this.port = port;
}
public void upload(String filePath) throws IOException {
// 建立连接
Socket socket = new Socket(host, port);
System.out.println("连接服务器成功");
// 获取文件名和文件大小
File file = new File(filePath);
String fileName = file.getName();
long fileSize = file.length();
System.out.println("文件名:" + fileName + ",大小:" + fileSize + " 字节");
// 发送文件名和文件大小
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF(fileName);
dos.writeLong(fileSize);
// 发送文件内容
FileInputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fis);
byte[] buffer = new byte[1024];
int length = -1;
while ((length = dis.read(buffer)) != -1) {
dos.write(buffer, 0, length);
}
dis.close();
fis.close();
dos.flush();
// 关闭连接
socket.shutdownOutput();
DataInputStream result = new DataInputStream(socket.getInputStream());
System.out.println("上传结果:" + result.readUTF());
result.close();
dos.close();
socket.close();
}
public static void main(String[] args) {
FileUploader uploader = new FileUploader("127.0.0.1", 8080);
try {
uploader.upload("D:\\test\\test.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个程序实现了从本地上传一个文件到服务器的功能。其中,需要替换的部分是 `host` 和 `port`,分别表示服务器的 IP 地址和端口号,以及 `filePath`,表示要上传的文件路径。另外,需要在服务器端编写相应的程序来接收上传的文件。