客户端:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client01 {
public static void main(String[] args) throws IOException, InterruptedException {
//1.创建socket,连接到服务端
Socket socket = new Socket("127.0.0.1",10000);
//2.获取输出流,向服务端发送信息
//字节输出流
OutputStream os = socket.getOutputStream();
//将输出流包装成打印流
PrintWriter pw = new PrintWriter(os);
//3.获取输入流,读取文件中的信息
//文件输入流
System.out.println("请你指定一个文件名:");
String path=new Scanner(System.in).nextLine();
//文件路径例子: D:\\WorkSpace1\\UsefulTest\\src\\cn\\homework\\Client01.java
File file=new File(path);
if(!file.exists()) {
System.out.println("文件不存在");
System.exit(0);
}
InputStream in = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(in,"utf-8");
BufferedReader br = new BufferedReader(isr);
String str = null;
while((str = br.readLine())!=null){
pw.write(str+"\r\n");
pw.flush();
}
System.out.println("文件发送成功");
pw.close();
br.close();
in.close();
os.close();
}
}
服务器端:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server01 {
public static void main(String[] args) throws IOException{
//1.创建服务端
ServerSocket ss = new ServerSocket(10000);
//接收客户端
Socket socket = null;
//2.获取输出流,向文件中写入内容
File f = new File("newIn.txt");
FileOutputStream out = new FileOutputStream(f);
String str = null;
//3.获取输入流
InputStream in = null;
InputStreamReader isr = null;
BufferedReader br = null;
String nextLine = System.getProperty("line.separator");
while(true){
socket = ss.accept();
in = socket.getInputStream();
isr = new InputStreamReader(in);
br = new BufferedReader(isr);
while((str = br.readLine())!=null){
out.write((str+nextLine).getBytes());
out.flush();
}
out.close();
System.exit(0);
}
}
}
先启动服务器,再启动客户端,程序可正常运行