Java文件上传相对路径代码示例
时间: 2024-02-26 17:48:37 浏览: 83
以下是Java文件上传相对路径代码示例:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class FileUploadClient {
public static void main(String[] args) throws IOException {
String host = "localhost"; // 服务器地址
int port = 8888; // 服务器端口号
String filePath = "test.txt"; // 文件路径
String destPath = "upload/test.txt"; // 上传目标路径
// 创建Socket对象
Socket socket = new Socket(host, port);
// 获取输出流
OutputStream outputStream = socket.getOutputStream();
// 获取文件输入流
File file = new File(filePath);
InputStream inputStream = new FileInputStream(file);
// 写入文件名和长度
outputStream.write(destPath.getBytes());
outputStream.write("\r\n".getBytes());
outputStream.write(String.valueOf(file.length()).getBytes());
outputStream.write("\r\n".getBytes());
// 写入文件内容
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
// 关闭流
inputStream.close();
outputStream.close();
socket.close();
}
}
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)