java基础——TCP网络编程实现文件的上传
Posted 名字真的很急用
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java基础——TCP网络编程实现文件的上传相关的知识,希望对你有一定的参考价值。
直接上代码:
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class 文件发送 {
public static void main(String[] args) throws IOException, IOException {
// TODO Auto-generated method stub
//创建客户端
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),8888);
//获取本地IO流
OutputStream outputStream = socket.getOutputStream();
//输入流 来获取要输出的流
BufferedInputStream buffer = new BufferedInputStream(new FileInputStream("d:\\\\aaa\\\\1.jpg"));
int leng =0;
byte data[] = new byte[1024];
while((leng=buffer.read(data))!=-1) {
outputStream.write(data, 0, leng);
}
socket.shutdownOutput();
//接收服务器端反馈的消息
InputStream inputStream = socket.getInputStream();
byte [] arr= new byte[1024];
int read =inputStream.read(arr);
System.out.println(new String(arr,0,read));
buffer.close();
outputStream.close();
socket.close();
inputStream.close();
}
}
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class 文件上传 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//TCP来回接收数据
ServerSocket socket = new ServerSocket(8888);
//侦听方法
Socket accept =socket.accept();
//获取输入流
InputStream inputStream = accept.getInputStream();
//本程序操作硬盘
BufferedOutputStream buffer = new BufferedOutputStream(new FileOutputStream("d:\\\\bbb\\\\2.jpg"));
byte [] data = new byte[1024];
//读写操作
int leng=0;
while((leng=inputStream.read(data))!=-1) {
buffer.write(data, 0, leng);
}
//告诉客户端写完了
OutputStream out = accept.getOutputStream();
out.write("over".getBytes());
//关流
buffer.close();
inputStream.close();
accept.close();
out.close();
}
}
重点看注释!!!!
以上是关于java基础——TCP网络编程实现文件的上传的主要内容,如果未能解决你的问题,请参考以下文章
Java-Web学习-Java基础-网络编程(TCP和UDP)附TCP实现通信