自己写的,客户端输入要发送的文件路径。
服务端输入接收文件保存的路径和文件名(本来想只需要输入路径,文件名和原来一样,但一下子思路有点空白。哈哈)
客户端:
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.FileInputStream;
- import java.net.Socket;
- import java.util.Scanner;
- public class FileTrans
- {
- public static void main(String[] args) throws Exception
- {
- Socket s = new Socket("192.168.1.101",10000);
- BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
- System.out.println("请输入要传输的文件的绝对路路径:");
- Scanner sc = new Scanner(System.in);
- String name = sc.next();
- BufferedInputStream bis = new BufferedInputStream(new FileInputStream(name));
- byte[] buf = new byte[1024];
- int len = 0;
- while((len=bis.read(buf))!=-1)
- {
- bos.write(buf,0,len);
- }
-
- bis.close();
- bos.close();
- s.close();
- sc.close();
-
- }
- }
复制代码
服务端:
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.FileOutputStream;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.Scanner;
- public class FileRece
- {
- public static void main(String[] args) throws Exception
- {
- ServerSocket ss = new ServerSocket(10000);
- Socket s = ss.accept();
- BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
- System.out.println("有人要给你发文件,请输入要保存的绝对路径,包括文件名和后缀");//创建新的文件用原来的名字还不是很熟练,先这样
- Scanner sc = new Scanner(System.in);
- String name = sc.nextLine();
- BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(name));
- byte[] buf = new byte[1024];
- int len = 0;
- while((len = bis.read(buf))!= -1)
- {
- bos.write(buf,0,len);
- }
- bos.close();
- bis.close();
- sc.close();
- ss.close();
- }
- }
复制代码
目前这个运行,会同时让客户端和服务端输入路径。接下来我还得修改,让服务端先输入保存路径,再让客户端传输。
|