跨网络实现文件的传输-使用流和socket
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Demo3 extends Thread{
//接收线程
InputStream is;
@Override
public void run() {
synchronized (Demo3.class){
byte[] arr = new byte[1024];
int len = 0;
try {
int read = is.read(arr);
//文件数据的输出
FileOutputStream os = new FileOutputStream("/Users/lifuwei/Desktop/Test/test"+System.currentTimeMillis()+".txt");
os.write(arr);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
import java.io.*;
public class Demo5 extends Thread{
//发送线程
OutputStream os;
@Override
public void run() {
synchronized (Demo5.class){
try {
//读取本地文件
FileInputStream msg = new FileInputStream("/Users/lifuwei/Desktop/Test/test.txt");
byte[] arr = new byte[1024];
int length = 0;
while ((length=msg.read(arr))!= -1){
String str = new String(arr, 0, length);
os.write(arr,0,length);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
//客户端
public class Demo4 {
public static void main(String[] args) throws Exception{
Socket socket = new Socket("localhost",8888);
OutputStream os = socket.getOutputStream();
InputStream is = socket.getInputStream();
Demo3 demo3 = new Demo3();
Demo5 demo5 = new Demo5();
demo3.is=is;
demo5.os=os;
demo3.start();
demo5.start();
}
}
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
//服务端
public class Demo6 {
public static void main(String[] args) throws Exception{
ServerSocket serverSocket = new ServerSocket(8888);
Socket server = serverSocket.accept();
InputStream is = server.getInputStream();
OutputStream os = server.getOutputStream();
Demo3 demo3 = new Demo3();
Demo5 demo5 = new Demo5();
demo3.is =is;
demo5.os = os;
demo3.start();
demo5.start();
}
}