java双向文件传输
时间: 2023-10-11 08:22:51 浏览: 63
Java文件传输
Java实现双向文件传输可以使用Socket编程,其中服务器端和客户端都需要编写代码实现文件传输。以下是一个简单的示例代码:
服务器端:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器已启动,等待客户端连接...");
Socket socket = serverSocket.accept();
System.out.println("客户端已连接...");
// 接收客户端发送的文件
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("server_receive.txt");
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.close();
is.close();
System.out.println("文件接收成功!");
// 发送文件给客户端
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream("server_send.txt");
buffer = new byte[1024];
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
fis.close();
os.close();
System.out.println("文件发送成功!");
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
客户端:
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
// 发送文件给服务器
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream("client_send.txt");
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
fis.close();
os.close();
System.out.println("文件发送成功!");
// 接收服务器发送的文件
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("client_receive.txt");
buffer = new byte[1024];
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.close();
is.close();
System.out.println("文件接收成功!");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
注意:以上代码只是一个简单的示例,没有进行错误处理和异常处理,请在实际应用中加强代码的健壮性。
阅读全文