Java多线程实现文件上传
Posted uoshuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java多线程实现文件上传相关的知识,希望对你有一定的参考价值。
import java.io.*;
import java.net.Socket;
/*
客户端:数据来自于文本文件,接收服务器反馈
*/
public class ClientDemo
public static void main(String[] args) throws IOException
//创建客户端Socket对象
Socket s = new Socket("192.168.1.66",10000);
//封装文本文件的数据
BufferedReader br = new BufferedReader(new FileReader("myNet\\\\InetAddressDemo.java"));
//封装输出流写数据
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String line;
while ((line=br.readLine())!=null)
bw.write(line);
bw.newLine();
bw.flush();
s.shutdownOutput();
//接收反馈
BufferedReader brClient = new BufferedReader(new InputStreamReader(s.getInputStream()));
String data = brClient.readLine(); //等待读取数据
System.out.println("服务器的反馈:" + data);
//释放资源
br.close();
s.close();
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/*
服务器:接收到的数据写入文本文件,给出反馈,代码用线程进行封装,为每一个客户端开启一个线程
*/
public class ServerDemo
public static void main(String[] args) throws IOException
//创建服务器Socket对象
ServerSocket ss = new ServerSocket(10000);
while (true)
//监听客户端连接,返回一个对应的Socket对象
Socket s = ss.accept();
//为每一个客户端开启一个线程
new Thread(new ServerThread(s)).start();
// ss.close();
import java.io.*;
import java.net.Socket;
public class ServerThread implements Runnable
private Socket s;
public ServerThread(Socket s)
this.s = s;
@Override
public void run()
try
//接收数据写到文本文件
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
// BufferedWriter bw = new BufferedWriter(new FileWriter("myNet\\\\Copy.java"));
//解决名称冲突问题
int count = 0;
File file = new File("myNet\\\\Copy["+count+"].java");
while (file.exists())
count++;
file = new File("myNet\\\\Copy["+count+"].java");
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
String line;
while ((line=br.readLine())!=null)
bw.write(line);
bw.newLine();
bw.flush();
//给出反馈
BufferedWriter bwServer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bwServer.write("文件上传成功");
bwServer.newLine();
bwServer.flush();
//释放资源
s.close();
catch (IOException e)
e.printStackTrace();
以上是关于Java多线程实现文件上传的主要内容,如果未能解决你的问题,请参考以下文章