Client
DownFilepackage francis.client.socket;
import java.io.*;
import java.net.*;
import java.nio.file.*;import javax.swing.JDialog;
import javax.swing.JOptionPane;//下载文件public class ClientDownFile{
public String ipaddress = new String(new ClientSetting().readSetting(1));
public int port = Integer.parseInt(new ClientSetting().readSetting(2));
byte[] readData = new byte[2048];
Socket socket;
public String path,name;
Path myfile;
 
public ClientDownFile(String name){
this.name = name;
{
try{
socket = new Socket();
socket.connect ( new InetSocketAddress (ipaddress,port));
path = new String("Down/"+name);
System.out.print(path);
myfile = Paths.get(path);
        OutputStream outputstream = socket.getOutputStream();// 输出流
        outputstream.write(2);
        outputstream.flush();
        readData = name.getBytes("utf-8");
        outputstream.write(readData); 
        outputstream.flush();
        InputStream inputstream = socket.getInputStream();
        outputstream = Files.newOutputStream(myfile,StandardOpenOption.CREATE);
        int temp = 0;
        while((temp=inputstream.read(readData))!=-1){ 
            outputstream.write(readData,0,temp); 
        } 
        outputstream.flush();
        outputstream.close();
        System.out.println("下载文件成功");
        socket.close();
        
        //提醒下载成功
        JDialog.setDefaultLookAndFeelDecorated(true);
  JOptionPane.showMessageDialog(null,"文件下载成功!","下载成功",
  JOptionPane.INFORMATION_MESSAGE);
                 }catch(Exception ex){
         ex.printStackTrace();
         //连接错误提示
            JDialog.setDefaultLookAndFeelDecorated(true);
       JOptionPane.showMessageDialog(null,"无法连接服务器,请检查地址与端口号!","错误",
     JOptionPane.ERROR_MESSAGE);
         }finally{
         System.out.println(socket.isClosed());
         System.out.println(socket.isConnected());
         }

}

}ListFresh:package francis.client.socket;
import java.io.*;
import java.net.*;
import java.nio.file.*;//从服务器端获取最新文件信息列表public class ClientListRefresh{
public String ipaddress = new String(new ClientSetting().readSetting(1));
public int port = Integer.parseInt(new ClientSetting().readSetting(2));
;
byte[] readData = new byte[2048];
Socket socket;
public String path,name;
Path myfile;
 
public ClientListRefresh(){
{
try{
socket = new Socket();
socket.connect ( new InetSocketAddress (ipaddress,port));
path = new String("filelist");
File listfile = new File("filelist");
if(listfile.exists())    
listfile.delete();
System.out.print(path);
myfile = Paths.get(path);
        OutputStream outputstream = socket.getOutputStream();// 输出流
        outputstream.write(3);
        outputstream.flush();
        InputStream inputstream = socket.getInputStream();
        outputstream = Files.newOutputStream(myfile,StandardOpenOption.CREATE);
        int temp = 0;
        while((temp=inputstream.read(readData))!=-1){ 
            outputstream.write(readData,0,temp); 
        } 
        outputstream.flush();
        outputstream.close();
        System.out.println("刷新成功");
        socket.close();
                 }catch(Exception ex){
         ex.printStackTrace();
         }finally{
         System.out.println(socket.isClosed());
         System.out.println(socket.isConnected());
         }

}

}SendFile:package francis.client.socket;
import java.io.*;
import java.net.*;
import java.nio.file.*;import javax.swing.JDialog;
import javax.swing.JOptionPane;//上传文件public class ClientSendFile{

byte[] readData = new byte[2048];
byte[] nafdata = new byte[2048];
Socket socket;
public String path,name,fileinfo;
public String ipaddress,port;
Path myfile;
 
public ClientSendFile(String path,String name,String fileinfo){
this.path = path;
this.name = name;
this.name = fileinfo;
{
try{
ipaddress = new String(new ClientSetting().readSetting(1));
port = new String(new ClientSetting().readSetting(2));
int n=Integer.parseInt(port);
System.out.println(ipaddress+port);
socket = new Socket();
socket.connect ( new InetSocketAddress (ipaddress,n));
System.out.print(path+"\n");
myfile = Paths.get(path);
InputStream inputstream = Files.newInputStream(myfile,StandardOpenOption.READ);
        OutputStream outputstream = socket.getOutputStream();// 输出流
        outputstream.write(1);
        outputstream.flush();
        
        String nameandfileinfo = new String(name+"///////"+fileinfo);
        nafdata = nameandfileinfo.getBytes("utf-8");
        outputstream.write(nafdata); 
        outputstream.flush();
        
        int temp = 0;
        while((temp=inputstream.read(readData))!=-1){ 
            outputstream.write(readData,0,temp); 
        } 
        outputstream.flush();
        outputstream.close();
        System.out.println("上传文件成功");
        socket.close();
        
        //提醒上传文件成功
        JDialog.setDefaultLookAndFeelDecorated(true);
  JOptionPane.showMessageDialog(null,"文件上传成功!","上传成功",
  JOptionPane.INFORMATION_MESSAGE);
                 }catch(Exception ex){
         ex.printStackTrace();
         }finally{
         System.out.println(socket.isClosed());
         System.out.println(socket.isConnected());
         }

}

}Setting:
package francis.client.socket;//设置import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;public class ClientSetting {

private String ipaddress,ipport;
private String stringdata; 
byte[] data = new byte[2048];
Path settingfile = Paths.get("setting");

//将参数写入文件
public void writeSetting(String ipaddress,String ipport)
{
this.ipaddress = ipaddress;
this.ipport = ipport;
stringdata = new String(ipaddress+" "+ipport);
try {
data = stringdata.getBytes("utf-8");
File myfile = new File("setting");
if(myfile.exists())    
myfile.delete();
OutputStream outputstream = Files.newOutputStream(settingfile,StandardOpenOption.CREATE);
outputstream.write(data);
outputstream.flush();
        outputstream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

//从文件中读取设置参数,tag=1返回地址,tag=2返回端口号
public String readSetting(int tag){
try{
InputStream inputstream = Files.newInputStream(settingfile,StandardOpenOption.READ);
inputstream.read(data);
            inputstream.close();
            stringdata = new String(data,"utf-8");
            stringdata = stringdata.trim();
            String[] returnit = stringdata.split(" ");
            ipaddress = returnit[0];
            ipport = returnit[1];
            } catch (IOException e){
             e.printStackTrace();
             }
if(tag == 1)
    return ipaddress;
if(tag == 2)
    return ipport;
return stringdata;
}

}Filelist:
package francis.filesystem;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;
public class FileList { public Vector<FileSystem> FileList = new Vector<FileSystem>();
public File filelist = new File("filelist");
public boolean getExist(){
return filelist.exists();
}

//获取文件信息列表
@SuppressWarnings("unchecked")
public Vector<FileSystem> getFileList(){
try{
ObjectInputStream inputstream = new ObjectInputStream(new FileInputStream(filelist));
FileList = (Vector<FileSystem>)inputstream.readObject();
inputstream.close();
} catch (Exception e){
e.getStackTrace();
}
return FileList;
}

//写入文件信息列表
public void writeFileList(Vector<FileSystem> FileList){
this.FileList = FileList;
try{
    ObjectOutputStream outputstream = new ObjectOutputStream(new FileOutputStream(filelist));
    outputstream.writeObject(FileList);
    outputstream.close();
} catch (Exception e){
e.getStackTrace();
}
}

//删除文件时从列表删除
public void deleteFile(String name){
FileList = new FileList().getFileList();
for(int i = 0;i < FileList.size();i++)
{
String filename = FileList.elementAt(i).getName();
if(filename.equals(name)){
FileList.remove(i);
String files = new String("Files/"+filename);
File fs =new File(files);
fs.delete();//删除效果
System.out.println("删除成功");
}
}
new FileList().writeFileList(FileList);
}

//重命名文件
public void renameFile(String name,String newname){
FileList = new FileList().getFileList();
for(int i = 0;i < FileList.size();i++)
{
String filename = FileList.elementAt(i).getName();
if(filename.equals(name)){
FileList.elementAt(i).setName(newname);
String files = new String("Files/"+filename);
String nfiles = new String("Files/"+newname);
File fs =new File(files);
fs.renameTo(new File(nfiles));
System.out.println("改名成功");
}
}
new FileList().writeFileList(FileList);
}

//修改文件描述信息
public void reinfoFile(String name,String info){
FileList = new FileList().getFileList();
for(int i = 0;i < FileList.size();i++)
{
String filename = FileList.elementAt(i).getName();
if(filename.equals(name)){
FileList.elementAt(i).setDescription(info);
System.out.println("改信息成功");
}
}
new FileList().writeFileList(FileList);
}

//增加文件总下载次数
public void increasedownFile(String name){
FileList = new FileList().getFileList();
for(int i = 0;i < FileList.size();i++)
{
String filename = FileList.elementAt(i).getName();
if(filename.equals(name)){
FileList.elementAt(i).setDowntimes();
System.out.println("添加下载成功");
}
}
new FileList().writeFileList(FileList);
}



}

解决方案 »

  1.   

    Filesystem:package francis.filesystem;import java.io.File;
    import java.io.Serializable;
    import java.util.Date;public class FileSystem implements Serializable { private static final long serialVersionUID = 1L; private String name;
    private long size;
    private Date uploaddate;
    private String description;
    private int downloadtimes = 0;
    private int nowdownloadtimes = 0;

    public FileSystem(String name){
    this.name = name;
    }

    //命名
    public void setName(String name){
    this.name = name;
    }

    //写入文件大小
    public void setSize(File file){
    this.size = file.length();
    }

    //写入上传时间
    public void setUploaddate(){
    this.uploaddate = new Date();
    }

    //写入描述信息
    public void setDescription(String description){
    this.description = description;
    }

    //写入下载次数
    public void setDowntimes(){
    downloadtimes = downloadtimes+1;
    }

    //获取文件名
    public String getName() {
    return name;
    }

    //获取文件大小
    public long getSize() {
    return size;
    }

    //获取文件上传时间
    public Date getUploaddate() {
    return uploaddate;
    } //获取文件描述
    public String getDescription() {
    return description;
    }

    //获取下载次数
    public int getDownloadTimes() {
    return downloadtimes;
    }

    //获取当前下载次数
    public int getNowDownloadTimes() {
    return nowdownloadtimes;
    }

    //判等
    public boolean equals(Object obj) {
    return name.equals(((FileSystem)obj).name);
    } public int hashCode() {
    int h = 0;
    for(int i = 0; i < name.length(); i++){
    h = h*31+name.charAt(i);
    }
    return h;
    } public String toString() {
    return "文件名: "+name+" 文件大小: "+size+
    " 上传时间: "+uploaddate+" 文件描述: "+description;
    }

    }
      

  2.   

    Server:FTPServerSocket:package francis.server.socket;
    import java.io.*;
    import java.net.*;//后台服务器public class FtpServerSocket{
    private ServerSocket ss;
    private int port = Integer.parseInt(new ServerSetting().readSetting(1));
    private ThreadPool threadpool;
    private int poolsize = 4;

    //创建线程池
    public FtpServerSocket() throws IOException{
    System.out.println(port);
    ss = new ServerSocket(port);
    threadpool= new ThreadPool(Runtime.getRuntime().availableProcessors() * poolsize);
    System.out.println("服务器启动");
    service();
    }

    //服务器服务函数
    public void service() {
    //以无限循环的方式等待用户请求
    while (true) {
    Socket socket=null;
    try {
    socket = ss.accept();
    //新开一个线程
    threadpool.execute(new Handler(socket));
    }catch (IOException e) {
    e.printStackTrace();
    }
    }
    }

    public static void main(String args[])throws IOException {
    new FtpServerSocket().service();
    }

    }
    Handler:package francis.server.socket;//服务器处理方法import java.io.IOException;import java.io.File;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.Socket;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.StandardOpenOption;
    import java.util.Vector;import francis.filesystem.FileSystem;
    import francis.filesystem.FileList;public class Handler implements Runnable{
    public Socket socket;
    public Handler(Socket socket){
    this.socket=socket;
    }
    Path myfile;
    byte[] readData = new byte[2048];
    byte[] nafData = new byte[2048];
    public Vector<FileSystem> FileList = new Vector<FileSystem>();

    //实现run()方法
    public void run(){
    try {
    System.out.println("New connection accepted " + socket.getInetAddress() + ":" +socket.getPort()); 
    //接受请求的类型
    InputStream inputstream = socket.getInputStream();
    int a = inputstream.read();
    System.out.println(a);

    //接受上传的文件
    if(a == 1)
    {
    inputstream.read(nafData);
    String nameandfileinfo = new String(nafData,"utf-8");
    nameandfileinfo = nameandfileinfo.trim();
    String[] naf = nameandfileinfo.split("///////");
    String name = naf[0];
    String fileinfo = naf[1];
    System.out.print(name+"\n");
    System.out.print(fileinfo+"\n");
    String path = new String("Files/"+name);
    myfile = Paths.get(path);

    OutputStream outputstream = Files.newOutputStream(myfile,StandardOpenOption.CREATE);
    int temp=0; 
    while((temp=inputstream.read(readData))!=-1){ 
    outputstream.write(readData,0,temp); 
    }
    outputstream.flush();
    outputstream.close();

    FileList = new FileList().getFileList();
    FileSystem newfile = new FileSystem(name);
    newfile.setUploaddate();
        newfile.setDescription(fileinfo);
        File mf = new File(path);
        newfile.setSize(mf);
        FileList.addElement(newfile);
        new FileList().writeFileList(FileList);

        socket.close();
    }

    //下载文件请求
    if(a == 2)
    {
    inputstream.read(readData);
    String name = new String(readData,"utf-8");
    name = name.trim();
    String path = new String("Files/"+name);
    myfile = Paths.get(path);
    inputstream = Files.newInputStream(myfile,StandardOpenOption.READ);
    OutputStream outputstream = socket.getOutputStream();
    int temp=0; 
    while((temp=inputstream.read(readData))!=-1){ 
    outputstream.write(readData,0,temp); 
    }
    outputstream.flush();
    outputstream.close();
    socket.close();
    new FileList().increasedownFile(name);
    }

    //获取服务器列表请求
    if(a == 3)
    {
    String path = new String("filelist");
    myfile = Paths.get(path);
    inputstream = Files.newInputStream(myfile,StandardOpenOption.READ);
    OutputStream outputstream = socket.getOutputStream();
    int temp=0; 
    while((temp=inputstream.read(readData))!=-1){ 
    outputstream.write(readData,0,temp); 
    }
    outputstream.flush();
    outputstream.close();
    socket.close();
    }
            }catch (IOException e) {
    e.printStackTrace();
    System.out.println("cao");
    }
    }

    }ServerListFresh:package francis.server.socket;//获取文件列表import java.util.Vector;import francis.filesystem.FileList;
    import francis.filesystem.FileSystem;public class ServerListFresh {
    public static Vector<FileSystem> FileList = new Vector<FileSystem>();
    public static void main(String[] args){
    FileList = new FileList().getFileList();
    System.out.print(FileList.elementAt(0).getName());
    }
    }ServerSetting:package francis.server.socket;//系统设置import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.StandardOpenOption;public class ServerSetting {

    private String port,size,client;
    private String stringdata; 
    byte[] data = new byte[2048];
    Path settingfile = Paths.get("setting");

    //将设置写入文件
    public void writeSetting(String port,String size,String client)
    {
    this.port = port;
    this.size = size;
    this.client = client;
    stringdata = new String(port+" "+client+" "+size);
    try {
    data = stringdata.getBytes("utf-8");
    File myfile = new File("setting");
    if(myfile.exists())    
    myfile.delete();
    OutputStream outputstream = Files.newOutputStream(settingfile,StandardOpenOption.CREATE);
    outputstream.write(data);
    outputstream.flush();
            outputstream.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    //从文件中获取设置信息,tag=1返回端口号,tag=2返回最大连接数,tag=3返回限制文件大小
    public String readSetting(int tag){
    try{
    InputStream inputstream = Files.newInputStream(settingfile,StandardOpenOption.READ);
    inputstream.read(data);
                inputstream.close();
                stringdata = new String(data,"utf-8");
                stringdata = stringdata.trim();
                String[] returnit = stringdata.split(" ");
                port = returnit[0];
                client = returnit[1];
                size = returnit[2];
                } catch (IOException e){
                 e.printStackTrace();
                 }
    if(tag == 1)
        return port;
    if(tag == 2)
        return client;
    if(tag == 3)
    return size;

    return stringdata;
    }

    }ThreadPool:package francis.server.socket;
    import java.util.LinkedList;public class ThreadPool extends ThreadGroup { private boolean isClosed = false;   //线程池初始为非关闭状态
    private LinkedList<Runnable> workQueue;   //工作队列
    private static int threadPoolID;     //线程池ID
    private int threadID;    //工作线程ID

    public ThreadPool(int poolSize) {     //参数指定线程池中的工作线程数目
    super("ThreadPool-" + (threadPoolID++));
    setDaemon(true);    //守护线程
    workQueue = new LinkedList<Runnable>();     //创建工作队列
    for(int i = 0; i<poolSize; i++) {
    new WorkThread().start();     //创建并启动工作线程
    }
    }


    //向工作队列中加入一个新任务,由工作线程执行该任务 public synchronized void execute(Runnable task) {
    if(isClosed) {
    throw new IllegalStateException();        //线程池关闭则抛出IllegalStateException异常
    }
    if(task != null) {
    workQueue.add(task);
    notify();                  //唤醒正在getTask()方法中等待任务的工作线程
    }
    }


    //从工作线程中取出一个任务,工作线程会调用此方法 protected synchronized Runnable getTask() throws InterruptedException {
    while(workQueue.size() == 0) {
    if(isClosed) return null;
    wait();                //如果工作队列中没有任务,就等待任务
    }
    return workQueue.removeFirst();
    }

    //关闭线程池

    public synchronized void close() {
    if(!isClosed) {
    isClosed = true;
    workQueue.clear();     //清空工作队列
    interrupt();           //中断所有的工作线程,该方法继承自ThreadGroup类
    }
    }

    public void join() {
    synchronized(this) {
    isClosed = true;
    notifyAll();        //唤醒还在getTask()方法中等待任务的工作线程
    }
    Thread[] threads = new Thread[activeCount()];
    int count = enumerate(threads);           //enumerate方法继承自ThreadGroup类,获得线程组中当前所有活着的工作线程
    for(int i = 0; i<count; i++) {           //等待所有工作线程运行结束
    try { 
    threads[i].join();               //等待工作线程运行结束
    } catch(InterruptedException e) {

    }
    }
    }

    private class WorkThread extends Thread {
    public WorkThread() {
    super(ThreadPool.this, "WorkThread-" + (threadID++));
    }

    public void run() {
    while(!isInterrupted()) {       //isInterrupted()方法继承自Thread类,判断线程是否被终端              
    Runnable task = null;
    try {
    task = getTask();        //取出任务
    } catch(InterruptedException e) {

    }

    /*
     * 如果getTask()返回null或者线程执行getTask()时被中断,则结束此线程
     */
    if(task == null) return;  try { 
    task.run();      //运行任务,异常在catch代码块中捕获
    } catch(Throwable t) {
    t.printStackTrace();
    }
    }
    }
    }

    }
      

  3.   

    FileList:package francis.filesystem;import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.util.Vector;
    public class FileList { public Vector<FileSystem> FileList = new Vector<FileSystem>();
    public File filelist = new File("filelist");
    public boolean getExist(){
    return filelist.exists();
    }

    //获取文件信息列表
    @SuppressWarnings("unchecked")
    public Vector<FileSystem> getFileList(){
    try{
    ObjectInputStream inputstream = new ObjectInputStream(new FileInputStream(filelist));
    FileList = (Vector<FileSystem>)inputstream.readObject();
    inputstream.close();
    } catch (Exception e){
    e.getStackTrace();
    }
    return FileList;
    }

    //写入文件信息列表
    public void writeFileList(Vector<FileSystem> FileList){
    this.FileList = FileList;
    try{
        ObjectOutputStream outputstream = new ObjectOutputStream(new FileOutputStream(filelist));
        outputstream.writeObject(FileList);
        outputstream.close();
    } catch (Exception e){
    e.getStackTrace();
    }
    }

    //删除文件时从列表删除
    public void deleteFile(String name){
    FileList = new FileList().getFileList();
    for(int i = 0;i < FileList.size();i++)
    {
    String filename = FileList.elementAt(i).getName();
    if(filename.equals(name)){
    FileList.remove(i);
    String files = new String("Files/"+filename);
    File fs =new File(files);
    fs.delete();//删除效果
    System.out.println("删除成功");
    }
    }
    new FileList().writeFileList(FileList);
    }

    //重命名文件
    public void renameFile(String name,String newname){
    FileList = new FileList().getFileList();
    for(int i = 0;i < FileList.size();i++)
    {
    String filename = FileList.elementAt(i).getName();
    if(filename.equals(name)){
    FileList.elementAt(i).setName(newname);
    String files = new String("Files/"+filename);
    String nfiles = new String("Files/"+newname);
    File fs =new File(files);
    fs.renameTo(new File(nfiles));
    System.out.println("改名成功");
    }
    }
    new FileList().writeFileList(FileList);
    }

    //修改文件描述信息
    public void reinfoFile(String name,String info){
    FileList = new FileList().getFileList();
    for(int i = 0;i < FileList.size();i++)
    {
    String filename = FileList.elementAt(i).getName();
    if(filename.equals(name)){
    FileList.elementAt(i).setDescription(info);
    System.out.println("改信息成功");
    }
    }
    new FileList().writeFileList(FileList);
    }

    //增加文件总下载次数
    public void increasedownFile(String name){
    FileList = new FileList().getFileList();
    for(int i = 0;i < FileList.size();i++)
    {
    String filename = FileList.elementAt(i).getName();
    if(filename.equals(name)){
    FileList.elementAt(i).setDowntimes();
    System.out.println("添加下载成功");
    }
    }
    new FileList().writeFileList(FileList);
    }



    }
    Filesystem:
    package francis.filesystem;import java.io.File;
    import java.io.Serializable;
    import java.util.Date;public class FileSystem implements Serializable { private static final long serialVersionUID = 1L; private String name;
    private long size;
    private Date uploaddate;
    private String description;
    private int downloadtimes = 0;
    private int nowdownloadtimes = 0;

    public FileSystem(String name){
    this.name = name;
    }

    //命名
    public void setName(String name){
    this.name = name;
    }

    //写入文件大小
    public void setSize(File file){
    this.size = file.length();
    }

    //写入上传时间
    public void setUploaddate(){
    this.uploaddate = new Date();
    }

    //写入描述信息
    public void setDescription(String description){
    this.description = description;
    }

    //写入下载次数
    public void setDowntimes(){
    downloadtimes = downloadtimes+1;
    }

    //获取文件名
    public String getName() {
    return name;
    }

    //获取文件大小
    public long getSize() {
    return size;
    }

    //获取文件上传时间
    public Date getUploaddate() {
    return uploaddate;
    } //获取文件描述
    public String getDescription() {
    return description;
    }

    //获取下载次数
    public int getDownloadTimes() {
    return downloadtimes;
    }

    //获取当前下载次数
    public int getNowDownloadTimes() {
    return nowdownloadtimes;
    }

    //判等
    public boolean equals(Object obj) {
    return name.equals(((FileSystem)obj).name);
    } public int hashCode() {
    int h = 0;
    for(int i = 0; i < name.length(); i++){
    h = h*31+name.charAt(i);
    }
    return h;
    } public String toString() {
    return "文件名: "+name+" 文件大小: "+size+
    " 上传时间: "+uploaddate+" 文件描述: "+description;
    }

    }