文件传输 Java实现,附源码

要求:
客户端实现功能:注册、登陆、上传文件、下载文件
服务器端实现功能:保存用户信息、处理用户上传和下载文件请求、保存用户上传文件、上传和下载文件前确保成功先判断空间是否足够。

介绍:
客户端文本框内输类似于linux指令,即可进行相应操作。
如:上传 put 文件名
下载 get 文件名

语言:Java
Swing、多线程、Socket(TCP)
注:我的电脑分辨率是2700*2500,客户端不能正常显示就得修改相应的setBound方法参数。

在这里插入图片描述

bug:不能上传名称带有空格的文件,原因(解决办法:在上传文件和下载文件部分,原本是用split(" ")切分,可以换成substring(3).trim(),跳过get或者put,删除多余空格)

客户端:

package client;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientFrame {
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     ClientFrame window = new ClientFrame();
     window.frame.setVisible(true);
     window.runInstruct("ls");
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }
 private JFrame frame;
 private JTextField textField;
 private JLabel resultLabel;
 private JTextArea clientArea;
 private JTextArea serverArea;
 private String defaultpath="C:/";
 private String path=defaultpath;
 private Socket socket;
 private Font defaultFont=new Font("楷体",Font.PLAIN,40);
 private InputStream istream;
 private OutputStream ostream;
 private BufferedReader in;
 private BufferedWriter out;
 private boolean login=false;
 public ClientFrame() throws UnknownHostException, IOException {
  initialize();
  socket=new Socket("127.0.0.1",6666);
  istream=socket.getInputStream();
  ostream=socket.getOutputStream();
  in = new BufferedReader(new InputStreamReader(istream));
  out=new BufferedWriter(new OutputStreamWriter(ostream));
 }
 private void initialize() {
  frame = new JFrame();
  frame.setBounds(200, 200, 2000, 1300);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.getContentPane().setLayout(null);
  frame.setTitle("输入help查看指令");
  frame.addWindowListener(new WindowAdapter() {
       public void windowClosing(WindowEvent e) {
        send("close");
        System.exit(0);
       }
     });
  clientArea = new JTextArea();
  clientArea.setBounds(0, 100, 900, 600);
  JScrollPane clientScrollPane=new JScrollPane(clientArea);
  clientScrollPane.setBounds(0, 100, 900, 600);
  frame.getContentPane().add(clientScrollPane);
  
  serverArea = new JTextArea();
  serverArea.setBounds(1100, 100, 900, 600);
  serverArea.setFont(defaultFont);
  serverArea.setText("\n\n\n\n\n\n\t\t  [空]");
  JScrollPane serverScrollPane=new JScrollPane(serverArea);
  serverScrollPane.setBounds(1100, 100, 900, 600);
  frame.getContentPane().add(serverScrollPane);
  resultLabel = new JLabel("result");
  resultLabel.setFont(defaultFont);
  resultLabel.setBounds(0, 750, 2000, 100);
  frame.getContentPane().add(resultLabel);
  textField = new JTextField();
  //回车键事件监听
  textField.addKeyListener(new KeyAdapter() {
   @Override
   public void keyPressed(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_ENTER) {
     try {
      runInstruct(textField.getText());
     } catch (IOException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
     }
    }
   }
  });
  textField.setFocusable(true);
  textField.setBounds(0, 900, 2000, 100);
  textField.setFont(defaultFont);
  frame.getContentPane().add(textField);
  textField.setColumns(10);
  JButton sendButton = new JButton("Send");
  sendButton.setBounds(1800, 1100, 200, 100);
  //按钮事件监听
  sendButton.addActionListener(new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent e) {
    try {
     runInstruct(textField.getText());
    } catch (IOException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
    }
   }
  });
  frame.getContentPane().add(sendButton);
  JLabel label = new JLabel("客户端文件");
  label.setBounds(300, 20, 300, 50);
  label.setFont(defaultFont);
  frame.getContentPane().add(label);
  JLabel label_1 = new JLabel("服务器文件");
  label_1.setBounds(1400, 20, 300, 50);
  label_1.setFont(defaultFont);
  frame.getContentPane().add(label_1);
  JLabel label_2 = new JLabel(">>>");
  label_2.setBounds(970, 300, 100, 100);
  label_2.setFont(defaultFont);
  frame.getContentPane().add(label_2);
  JLabel label_3 = new JLabel("<<<");
  label_3.setBounds(970, 370, 100, 100);
  label_3.setFont(defaultFont);
  frame.getContentPane().add(label_3);
 }
 private void runInstruct(String instruct) throws IOException {
  textField.setText("");
  String[] parts = instruct.split(" ");
  String line;
  String[] addr;
  switch(parts[0]) {
   case "help":
    clientArea.setFont(defaultFont);
    clientArea.setText("");
    clientArea.append("signup 用户名 密码   注册账号\n");
    clientArea.append("login 用户名 密码   登录账号\n");
    clientArea.append("ls/cls 展示客户端当前目录文件列表\n");
    clientArea.append("cd/ccd 展示客户端目录跳转\n");
    clientArea.append("pwd/cpwd 展示当前客户端路径\n");
    clientArea.append("mkdir/cmkdir 在客户端创建文件夹\n");
    clientArea.append("sls 展示服务器端当前目录文件列表\n");
    clientArea.append("scd 展示服务器目录跳转\n");
    clientArea.append("spwd 展示当前服务器端路径\n");
    clientArea.append("smkdir 在服务器端创建文件夹\n");
    clientArea.append("put 文件名   上传文件\n");
    clientArea.append("get 文件名   下载文件\n");
    break;
   case "ls": case "cls":
    if(path.endsWith("/"))
     showFiles(path,clientArea);
    else
     showFiles(path+"/",clientArea);
    break;
   case "sls":
    if(login==false) {
     resultLabel.setText("请先登录");
     return;
    }
    send("sls");
    break;
   case "cd": case "ccd":
    if(parts.length==1) {
     resultLabel.setText("请输入路径");
     return;
    }
    String[] splits = parts[1].split("/");
    if(parts[1].startsWith("c:")||parts[1].startsWith("C:")
      ||parts[1].startsWith("d:")||parts[1].startsWith("D:")
      ||parts[1].startsWith("e:")||parts[1].startsWith("E:")
      ||parts[1].startsWith("f:")||parts[1].startsWith("F:")
      ||parts[1].startsWith("g:")||parts[1].startsWith("G:")) {
     if(new File(parts[1]).exists()==false) {
      resultLabel.setText("路径不存在"+parts[1]);
      return;
     }
     path=parts[1];
     showFiles(path,clientArea);
     return;
    }else if(!splits[0].equals("..")){
     StringBuilder sb=new StringBuilder(path);
     for(String tmp:splits) {
      sb.append(tmp+"/");
     }
     String tmppath=sb.toString();
     if(new File(tmppath).exists()==false) {
      resultLabel.setText("路径不存在"+tmppath);
      return;
     }else {
      path=tmppath;
      showFiles(path,clientArea);
     }
    }else {
     String[] ps = path.split("/");
     if(ps.length<splits.length) {
      path=ps[0]+"/";
      showFiles(path,clientArea);
      return;
     }
     StringBuilder sb=new StringBuilder(ps[0]+"/");
     for(int i=1;i<ps.length-splits.length;i++) {
      sb.append(ps[i]+"/");
     }
     path=sb.toString();
     showFiles(path, clientArea);
    }
    break;
   case "scd":
    send(instruct);
    send("sls");
    break;
   case "pwd":
   case "cpwd":
    resultLabel.setText("客户端当前路径:"+path);
    break;
   case "spwd":
    resultLabel.setText("服务器当前路径:"+send("spwd"));
    break;
   case "login":
    if(parts.length<3) {
     resultLabel.setText("请按照格式输入用户名和命名   格式:login 用户名 密码");
     return;
    }
    line=send(instruct);
    resultLabel.setText(line);
    if(line.startsWith("ERROR")) {
     return;
    }
    send("sls");
    login=true;
    break;
   case "signup":
    if(parts.length<3) {
     resultLabel.setText("请按照格式输入用户名和命名   格式:signup 用户名 密码");
     return;
    }
    line=send(instruct);
    resultLabel.setText(line);
    if(line.startsWith("ERROR")) {
     return;
    }
    login=true;
    send("sls");
    break;
   case "mkdir": 
   case "cmkdir":
    if(parts.length<2) {
     resultLabel.setText("请输入路径");
     return;
    }
    if(new File(path+(parts[1].startsWith("/")?parts[1].substring(1,parts[1].length()):parts[1])).mkdirs()==false) {
     resultLabel.setText("目录创建失败,路径:"+path+(parts[1].startsWith("/")?parts[1].substring(1,parts[1].length()):parts[1]));
     return;
    }
    runInstruct("ls");
    resultLabel.setText("创建成功");
    break;
   case "smkdir":
    if(parts.length<2) {
     resultLabel.setText("请输入路径");
     return;
    }
    line=send(instruct);
    send("sls");
    resultLabel.setText(line);
    break;
   case "rmdir":
   case "crmdir":
    if(parts.length<2) {
     resultLabel.setText("请输入路径");
     return;
    }
    if(new File(path+(parts[1].startsWith("/")?parts[1].substring(1,parts[1].length()):parts[1])).exists()==false) {
     resultLabel.setText("目录不存在,路径:"+path+(parts[1].startsWith("/")?parts[1].substring(1,parts[1].length()):parts[1]));
     return;
    }
    if(new File(path+(parts[1].startsWith("/")?parts[1].substring(1,parts[1].length()):parts[1])).delete()==false) {
     resultLabel.setText("目录删除失败,路径:"+path+(parts[1].startsWith("/")?parts[1].substring(1,parts[1].length()):parts[1]));
     return;
    }
    runInstruct("ls");
    resultLabel.setText("删除成功");
    break;
   case "srmdir":
    if(parts.length<2) {
     resultLabel.setText("请输入路径");
     return;
    }
    line=send(instruct);
    send("sls");
    resultLabel.setText(line);
    break;
   case "put":
    //未输入路径
    if(parts.length<2) {
     resultLabel.setText("请输入路径");
     return;
    }
    File file=new File(path+(parts[1].startsWith("/")?parts[1].substring(1,parts[1].length()):parts[1]));
    //文件不存在
    if(file.exists()==false) {
     resultLabel.setText("文件"+(path+(parts[1].startsWith("/")?parts[1].substring(1,parts[1].length()):parts[1])+"不存在"));
     return;
    }
    if(file.isDirectory()) {
     resultLabel.setText("文件"+(path+(parts[1].startsWith("/")?parts[1].substring(1,parts[1].length()):parts[1])+"为文件夹,不能上传"));
     return;
    }
    line=send(instruct);
    //系统空间不够
    if(file.length()>Long.parseLong(line)) {
     resultLabel.setText("文件太大,服务器无法储存,文件大小"+new File(path).length()+" 系统剩余"+Long.parseLong(line));
     out.write("ERROR");
     out.newLine();
     out.flush();
     return;
    }
    resultLabel.setText("文件大小"+file.length()+"开始发送....");
    //告诉系统空间足够
    out.write("enough");
    out.newLine();
    out.flush();
    //读取IP和端口号
    line=in.readLine();
    addr = line.split(" ");
    new PutFileThread(path+(parts[1].startsWith("/")?parts[1].substring(1,parts[1].length()):parts[1]),new Socket(addr[0],Integer.parseInt(addr[1]))).start();
    break;
   case "get":
    if(parts.length<2) {
     resultLabel.setText("请输入路径");
     return;
    }
    line=send(instruct);
    //遇到错误
    if(line.startsWith("ERROR")) {
     resultLabel.setText(line);
     return;
    }
    //判断系统客户端空间是否够用
    if(new File(path).getFreeSpace()<Long.parseLong(line)) {
     resultLabel.setText("系统硬盘大小不够");
     out.write("ERROR");
     out.newLine();
     out.flush();
     return;
    }
    //提示服务器硬盘大小足够
    out.write("enough");
    out.newLine();
    out.flush();
    resultLabel.setText("文件大小:"+(Long.parseLong(line)/1024.0/1024)+"M,开始接收....");
    //接收IP和端口
    line=in.readLine();
    if(line.startsWith("ERROR")) {
     resultLabel.setText(line);
     return;
    }
    addr = line.split(" ");
    new GetFileThread(path+(parts[1].startsWith("/")?parts[1].substring(1,parts[1].length()):parts[1]),new Socket(addr[0],Integer.parseInt(addr[1]))).start();
    break;
   default:
    resultLabel.setText("指令不存在:"+instruct);
  }
 }
 private String send(String data) {
  String line=null;
  try {
   out.write("#INSTRUCT#"+data);
   out.newLine();
   out.flush();
   if(data.equals("sls")) {
    int size=0;
    serverArea.setText("");
    while(!(line=in.readLine()).equals("#END#")) {
     size++;
     serverArea.append(line+"\n");
    }
    if(size==0) {
     serverArea.setText("\n\n\n\n\n\n\t\t  [空]");
     resultLabel.setText("共"+size+"个文件");
    }else {
     resultLabel.setText("共"+size+"个文件");
    }
    return null;
   }else {
    line = in.readLine();
    return line;
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return line;
 }
 class PutFileThread extends Thread{
  BufferedInputStream bis;
  BufferedOutputStream bos;
  public PutFileThread(String path,Socket sendSocket) throws IOException {
   bis=new BufferedInputStream(new FileInputStream(new File(path)));
   bos=new BufferedOutputStream(sendSocket.getOutputStream());
  }
  @Override
  public void run() {
   byte[] buff=new byte[1024];
   int len=0;
   try {
    while((len=bis.read(buff))!=-1) {
     bos.write(buff, 0, len);
    }
    bos.flush();
    runInstruct("sls");
    resultLabel.setText("上传成功");
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } finally {
    try {
     bis.close();
     bos.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
 }
 class GetFileThread extends Thread{
  BufferedInputStream bis;
  BufferedOutputStream bos;
  String path;
  public GetFileThread(String path,Socket getSocket) throws IOException {
   bis=new BufferedInputStream(getSocket.getInputStream());
   bos=new BufferedOutputStream(new FileOutputStream(new File(path)));
   this.path=path;
  }
  @Override
  public void run() {
   byte[] buff=new byte[1024];
   int len=0;
   try {
    while((len=bis.read(buff))!=-1) {
     bos.write(buff, 0, len);
    }
    bos.flush();
    runInstruct("ls");
    resultLabel.setText("下载成功");
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } finally {
    try {
     bis.close();
     bos.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
 }
 private void showFiles(String path,JTextArea area) {
  File file = new File(path);
  File[] listFiles = file.listFiles();
  resultLabel.setText("");
  area.setText("");
  area.setFont(defaultFont);
  int size=0;
  for(File tmp:listFiles) {
   area.append(tmp.getName()+"\n");
   size++;
  }
  resultLabel.setText("共"+size+"个文件");
  if(size==0) {
   area.setText("\n\n\n\n\n\n\t\t  [空]");
  }
 }
}

服务器:

package server;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
public class Server extends Thread{
 public static void main(String[] args) throws IOException {
  new Server().start();
 }
 private final String BASE_PATH="C:/FileSystem";
 private final String SYSTEM_DATA="C:/FileSystem/user/dat.txt";
 private final int PORT=6666;
 private final String IP="127.0.0.1";
 private HashMap<String,String> users;
 private ServerSocket listenSocket;
 Server() throws IOException{
  listenSocket=new ServerSocket(PORT);
  File file = new File(BASE_PATH);
  if(!file.exists()) {
   boolean success = file.mkdirs();
   if(!success) {
    System.out.println("系统目录创建失败");
    return;
   }
  }
  System.out.println("系统目录创建成功");
  file=new File("C:/FileSystem/user");
  if(!file.exists()) {
   boolean success = file.mkdirs();
   if(!success) {
    System.out.println("系统目录user创建失败");
    return;
   }
  }
  System.out.println("系统文件创建成功");
  file=new File(SYSTEM_DATA);
  if(!file.exists()) {
   boolean success = file.createNewFile();
   if(!success) {
    System.out.println("系统目录创建失败");
    return;
   }
  }
  users=new HashMap<String, String>();
  BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(SYSTEM_DATA))));
  System.out.println("初始化用户数据");
  String line=null;
  while((line=br.readLine())!=null) {
   if(line.trim().equals(""))
    continue;
   if(line.endsWith("\n")) {
    line=line.substring(0,line.length()-1);
   }
   System.out.println(line);
   String[] datas = line.split("[ ]+");
   users.put(datas[0], datas[1]);
  }
  System.out.println("用户数据初始化完成");
 }
 @Override
 public void run() {
  while(true) {
   try {
    //等待用户连接
    Socket client = listenSocket.accept();
    System.out.println("接收到一个客户端连接");
    //交给线程管理
    new HandleThread(client).start();
   } catch (IOException e) {
    e.printStackTrace();
   }
   
  }
 }
 class HandleThread extends Thread{
  private InputStream istream;
  private OutputStream ostream;
  private BufferedReader in;
  private BufferedWriter out;
  private Socket client;
  private String path="/";
  public HandleThread(Socket client) throws IOException {
   this.client=client;
   istream=client.getInputStream();
   ostream=client.getOutputStream();
   in = new BufferedReader(new InputStreamReader(istream));
   out=new BufferedWriter(new OutputStreamWriter(ostream));
  }
  @Override
  public void run() {
   System.out.println("线程初始化成功");
   String line=null;
   try {
    //读取用户指令
    while((line=in.readLine())!=null) {
     //用户断开连接
     if(line.equals("#INSTRUCT#close")) {
      System.out.println("客户端"+client+"断开连接");
      return;
     }
     runInstruct(line.trim());
    }
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }finally {
    try {
     if(client!=null)
      client.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
  private void runInstruct(String instruct) throws IOException {
   if(!instruct.startsWith("#INSTRUCT#")) {
    return;
   }
   instruct=instruct.substring(10,instruct.length());
   System.out.println("客户端"+client+"发来指令"+instruct+"\n");
   String[] parts = instruct.split(" ");
   int port;
   File file;
   switch(parts[0]) {
    case "signup"://注册
     if(parts.length<2) {
      out.write("ERROR请完整输入用户名和密码");
      out.newLine();
      out.flush();
      return;
     }
     if(users.containsKey(parts[1])) {
      out.write("ERROR用户"+parts[1]+"已存在");
      out.newLine();
      out.flush();
      return;
     }
     writeToSystemFile(parts[1]+" "+parts[2]);
     users.put(parts[1],parts[2]);
     file=new File(BASE_PATH+"/home/"+parts[1]);
     if(file.mkdirs()==false) {
      out.write("ERROR家目录创建失败");
      out.newLine();
      out.flush();
      return;
     }
     path="/home/"+parts[1];
     out.write("注册成功,已登录");
     out.newLine();
     out.flush();
     break;
    case "login"://登陆
     if(!users.containsKey(parts[1])) {
      System.out.println("登陆失败");
      out.write("ERROR用户"+parts[1]+"不存在");
      out.newLine();
      out.flush();
     }else if(users.get(parts[1]).equals(parts[2])) {
      out.write("登录成功");
      out.newLine();
      out.flush();
      path="/home/"+parts[1];
     }else {
      System.out.println("登陆失败");
      out.write("ERROR用户名或密码错误");
      out.newLine();
      out.flush();
     }
     break;
    case "sls"://查看服务器文件列表
     file = new File(BASE_PATH+path);
     System.out.println(BASE_PATH+path);
     File[] files = file.listFiles();
     for(File f:files) {
      out.write(f.getName());
      out.newLine();
      out.flush();
     }
     out.write("#END#");
     out.newLine();
     out.flush();
     break;
    case "spwd"://查看当前用户路径
     out.write(path);
     out.newLine();
     out.flush();
     break;
    case "scd"://切换目录
     if(parts.length<2) {
      out.write("请输入路径");
      out.newLine();
      out.flush();
      return;
     }
     String[] splits = parts[1].split("/");
     if(!splits[0].equals("..")){
      StringBuilder sb=new StringBuilder(path);
      for(String tmp:splits) {
       if(!tmp.trim().equals("")) {
        sb.append("/"+tmp);
       } 
      }
      sb.append("/");
      String tmppath=sb.toString();
      System.out.println(client+"切换路径"+BASE_PATH+tmppath);
      if(new File(BASE_PATH+tmppath).exists()==false) {
       out.write("路径不存在"+tmppath);
       out.newLine();
       out.flush();
      }else {
       path=tmppath;
       out.write("切换成功,当前路径:"+path);
       out.newLine();
       out.flush();
      }
     }else {
      String[] ps = path.split("/");
      if(ps.length<splits.length) {
       path="/";
       out.write("切换成功,当前路径:"+path);
       out.newLine();
       out.flush();
       return;
      }
      StringBuilder sb=new StringBuilder("/"+ps[0]);
      for(int i=1;i<ps.length-splits.length;i++) {
       sb.append("/"+ps[i]);
      }
      System.out.println(client+"切换路径"+BASE_PATH+path);
      if(new File(BASE_PATH+sb.toString()).exists()==false) {
       out.write("切换失败,路径错误:"+path);
       out.newLine();
       out.flush();
       return;
      }
      path=sb.toString();
      out.write("切换成功,当前路径:"+path);
      out.newLine();
      out.flush();
     }
     break;
    case "smkdir"://创建目录
     if(new File(BASE_PATH+path+(parts[1].startsWith("/")?parts[1]:"/"+parts[1])).mkdirs()==false) {
      out.write("目录:"+(BASE_PATH+path+(parts[1].startsWith("/")?parts[1]:"/"+parts[1]))+"创建失败");
      out.newLine();
      out.flush();
      return;
     }
     out.write("创建成功");
     out.newLine();
     out.flush();
     break;
    case "srmdir"://删除目录
     if(new File(BASE_PATH+path+(parts[1].startsWith("/")?parts[1]:"/"+parts[1])).exists()==false) {
      out.write("目录:"+(BASE_PATH+path+(parts[1].startsWith("/")?parts[1]:"/"+parts[1]))+"不存在");
      out.newLine();
      out.flush();
      return;
     }
     if(new File(BASE_PATH+path+(parts[1].startsWith("/")?parts[1]:"/"+parts[1])).delete()==false) {
      out.write("目录:"+(BASE_PATH+path+(parts[1].startsWith("/")?parts[1]:"/"+parts[1]))+"删除失败");
      out.newLine();
      out.flush();
      return;
     }
     out.write("删除成功");
     out.newLine();
     out.flush();
     break;
    case "put"://上传文件
     //向客户端发送系统剩余空间大小
     out.write(""+new File(BASE_PATH).getFreeSpace());
     out.newLine();
     out.flush();
     //系统空间不够
     if(!in.readLine().equals("enough"))
      return;
     //随机生成可用端口
     port=9999;
     while(isPortUsing(IP,port)==true) {//端口被占用
      port=(int)(Math.random()*10000+5000);
     }
     new PutFileThread(new ServerSocket(port), 
       BASE_PATH+path+(parts[1].startsWith("/")?parts[1]:"/"+parts[1])).start();
     out.write(IP+" "+port);
     out.newLine();
     out.flush();
     break;
    case "get"://下载文件
     System.out.println(BASE_PATH+path+(parts[1].startsWith("/")?parts[1]:"/"+parts[1]));
     file=new File(BASE_PATH+path+(parts[1].startsWith("/")?parts[1]:"/"+parts[1]));
     if(file.exists()==false) {
      System.out.println("文件不存在");
      out.write("ERROR文件:"+(BASE_PATH+path+(parts[1].startsWith("/")?parts[1]:"/"+parts[1]))+"不存在");
      out.newLine();
      out.flush();
      return;
     }
     if(file.isDirectory()==true) {
      System.out.println("不能get目录");
      out.write("ERROR文件:"+(BASE_PATH+path+(parts[1].startsWith("/")?parts[1]:"/"+parts[1]))+"为文件夹,不能下载");
      out.newLine();
      out.flush();
      return;
     }
     //返回文件大小
     out.write(""+file.length());
     out.newLine();
     out.flush();
     //用户硬盘大小不够
     if(!in.readLine().equals("enough")) {
      return;
     }
     port=9999;
     while(isPortUsing(IP,port)==true) {//端口被占用
      port=(int)(Math.random()*10000+5000);
     }
     
     new GetFileThread(new ServerSocket(port), 
       BASE_PATH+path+(parts[1].startsWith("/")?parts[1]:"/"+parts[1])).start();
     out.write(IP+" "+port);
     out.newLine();
     out.flush();
     break;
    default://指令不存在
     out.write("指令"+instruct+"不存在");
     out.newLine();
     out.flush();
   }
  }
 }
 class PutFileThread extends Thread{
  BufferedInputStream bis;
  BufferedOutputStream bos;
  ServerSocket serverSocket;
  String path;
  public PutFileThread(ServerSocket serverSocket,String path) {
   System.out.println("文件路径:"+path);
   this.serverSocket=serverSocket;
   this.path=path;
  }
  @Override
  public void run() {
   Socket socket = null;
   byte[] buff=new byte[1024];
   int len=0;
   try {
    socket = serverSocket.accept();
    this.bis=new BufferedInputStream(socket.getInputStream());
    this.bos=new BufferedOutputStream(new FileOutputStream(path));
    while((len=bis.read(buff))!=-1) {
     bos.write(buff, 0, len);
    }
    bos.flush();
    System.out.println("读取完毕");
   } catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   }finally {
    try {
     bis.close();
     bos.close();
     serverSocket.close();
     socket.close();
     
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
 }
 class GetFileThread extends Thread{
  BufferedInputStream bis;
  BufferedOutputStream bos;
  ServerSocket serverSocket;
  String path;
  public GetFileThread(ServerSocket serverSocket,String path) {
   System.out.println("文件路径:"+path);
   this.serverSocket=serverSocket;
   this.path=path;
  }
  @Override
  public void run() {
   Socket socket = null;
   byte[] buff=new byte[1024];
   int len=0;
   try {
    socket = serverSocket.accept();
    this.bis=new BufferedInputStream(new FileInputStream(path));
    this.bos=new BufferedOutputStream(socket.getOutputStream());
    while((len=bis.read(buff))!=-1) {
     bos.write(buff, 0, len);
    }
    bos.flush();
    System.out.println("传输完毕,文件名:"+path+" 文件大小:"+new File(path).length()/1024.0/1024.0+"M");
   } catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   }finally {
    try {
     bis.close();
     bos.close();
     serverSocket.close();
     socket.close();
     
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
 }
 private void writeToSystemFile(String user) {
  BufferedWriter bw = null;
  try {
   bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(SYSTEM_DATA),true)));
   bw.write(user);
   bw.newLine();
   bw.flush();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally {
   try {
    if(bw!=null)
     bw.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  } 
 }
 @SuppressWarnings("resource")
 public static boolean isPortUsing(String host,int port) throws UnknownHostException {
  boolean flag = false;
  InetAddress theAddress = InetAddress.getByName(host);
  try {
   Socket socket = new Socket(theAddress,port);
   flag = true;
  } catch (IOException e) {
   
  }
  return flag;
 }
}

由于上传时代码有/**注释,导致网站卡住,所以我把部分注释删了,我将整个文件(完整版,包括注释)打包好已上传csdn,欢迎下载,如有问题,欢迎指出。

https://download.csdn.net/download/D1124615130/12614440

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值