admin 管理员组文章数量: 1184232
这里是利用JavaAPI中的Socket和输入输出流实现两台电脑之间文件的传递
首先需要有一个发送方,即服务器端,服务器提供URL地址还有端口号
然后需要一个接收方,即客户端,客户端负责使用URL和端口号连接服务器
最后我觉得代码里面的注解很详细了
帅气与美貌共存的博主就不多加叨叨了[滑稽斜眼笑]
实例代码:
文件发送方(Send.java):
//筱白痴//文件发送方
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.Socket;
publicclass Send {
publicstaticvoidmain(String[] args) {
File src; //需要传送的文件
Socket socket; //套接字
FileInputStream open; //读取文件
FileOutputStream out; //传送文件try {
//需要传输的文件
src = new File("E:\\shaohan.png");
open = new FileInputStream(src);
//连接服务器
socket = new Socket("127.0.0.1", 2017);
out = (FileOutputStream)socket.getOutputStream();
//开始传送byte[] b = newbyte[64];
int n = open.read(b);
int start = (int)System.currentTimeMillis();
while (n != -1) {
out.write(b, 0, n);
n = open.read(b);
}
int end = (int)System.currentTimeMillis();
System.out.println( "发送花费的时间:" + (end-start));
//关闭流out.close();
socket.close();
open.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
文件接收方(Receive.java):
//筱白痴:20171023//接收指定文件
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.Socket;
import java.net.ServerSocket;
publicclass Receive {
publicstaticvoidmain(String[] args) {
File target; //接收到的文件保存的位置
FileOutputStream save; //将接收到的文件写入电脑
FileInputStream in; //读取穿送过来的数据文件
ServerSocket server; //服务器
Socket socket; //套接字//处理客户端的请求try {
//接受前文件的准备
target = new File("E:\\tempshaohan.png");
save = new FileOutputStream(target);
server = new ServerSocket(2017); //服务端口//等待客户端的呼叫
System.out.println("等待客户端的呼叫");
socket = server.accept(); //阻塞in = (FileInputStream)socket.getInputStream();
//接收数据byte[] b = newbyte[64];
int n = in.read(b);
int start = (int)System.currentTimeMillis();
while (n != -1) {
save.write(b, 0, n); //写入指定地方
n = in.read(b);
}
int end = (int)System.currentTimeMillis();
System.out.println("接收花费的时间:" + (end-start));
socket.close();
server.close();
in.close();
save.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
奥,对了,帅气与美貌并存的博主提醒一下在场的吃瓜码农
这服务器端的电脑和客户端的电脑要在同一局域网下才能实现传输哦
版权声明:本文标题:Java大法好!两台电脑间文件传输的简单解决方案 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1770733497a3536979.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论