file 传文件
时间: 2024-01-25 13:04:19 浏览: 21
要使用Java中的File传输文件,可以使用FileInputStream和FileOutputStream来实现。下面是一个简单的例子:
1. 服务端代码
```java
public class Server {
public static void main(String[] args) throws Exception {
FileInputStream fileInputStream = new FileInputStream(new File("file.txt"));
FileOutputStream fileOutputStream = new FileOutputStream(new File("file_copy.txt"));
byte[] buffer = new byte[1024];
int len;
while ((len = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
fileInputStream.close();
fileOutputStream.close();
}
}
```
2. 客户端代码
```java
public class Client {
public static void main(String[] args) throws Exception {
FileInputStream fileInputStream = new FileInputStream(new File("file.txt"));
FileOutputStream fileOutputStream = new FileOutputStream(new File("file_copy.txt"));
byte[] buffer = new byte[1024];
int len;
while ((len = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
fileInputStream.close();
fileOutputStream.close();
}
}
```
在这个例子中,服务端读取本地的file.txt文件,将内容写入到file_copy.txt文件中。客户端也是读取本地的file.txt文件,将内容写入到file_copy.txt文件中。
需要注意的是,这个例子只是一个简单的示例,实际应用中需要考虑更多的安全性和稳定性问题。同时,需要注意文件路径和文件名的设置。