这篇文章主要介绍了java如何使用Socket实现文件上传功能,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
具体内容如下
文件上传的步骤:
1、创建ServerSocket
2、调用accept获得客户端Socket
3、定义字节数组
4、创建文件输出流,获得客户端输入流
5、循环读取输入流的字节,写入到文件输出流
1、创建Socket
2、获得socket对象输出流
3、创建文件输入流
4、循环读取文件输入流字节,写入到输出流
服务器端:
public class FileServer {
public static final int PORT = 8888;
public static final String PATH = "D:\\upload\\";
public void start(){
System.out.println("start...");
try ( //创建服务器端对象
ServerSocket server = new ServerSocket(PORT);){
while (true){
Socket socket = server.accept();
try ( //创建文件输出流和网络输入流
DataInputStream in = new DataInputStream(socket.getInputStream());
//读取哭护短发来的文件名,创建文件输出流
FileOutputStream out = new FileOutputStream(PATH+in.readUTF())){
int len = 0;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) != -1){
out.write(buffer,0,len);
}
System.out.println("服务器保存完毕!");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new FileServer().start();
}
}
客户端:
public class FileClient {
/**
* 发送文件
*/
public void sendFile(String ip,int port,String path){
File file = new File(path);
try (
//创建连接,创建文件输入流,网络输出流
Socket socket = new Socket(ip,port);
InputStream in = new FileInputStream(path);
DataOutputStream out = new DataOutputStream(socket.getOutputStream())){
//先发送文件给服务器
out.writeUTF(file.getName());
out.flush();
//读取本地文件,写入到网络输出流中
int len = 0;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) != -1){
out.write(buffer,0,len);
}
System.out.println("客户端发送完毕!");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new FileClient().sendFile("192.168.31.226",8888,"C:\\Users\\admin\\Desktop\\C.txt");
}
}
实现效果:
感谢你能够认真阅读完这篇文章,希望小编分享的“java如何使用Socket实现文件上传功能”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。