使用java中的socket将文件从服务器下载到客户端

时间:2014-09-23 04:49:34

标签: java sockets

我有一些代码将文件从客户端上传到服务器并且工作正常,上传的文件保存在名为Server的Server文件夹中,现在想将服务器文件夹中存在的文件下载到客户端文件夹但不知道怎么做那。 请给予帮助

此服务器代码说明了从客户端到服务器的下载文件:

  public static void downloadFile() throws Exception{
    try {
        fileEvent = (FileEvent) inputStream.readObject();
        if (fileEvent.getStatus().equalsIgnoreCase("Error")) {
            System.out.println("Error occurred ..So exiting");
            System.exit(0);
        }
        String outputFile = fileEvent.getDestinationDirectory() + fileEvent.getFilename();
        if (!new File(fileEvent.getDestinationDirectory()).exists()) {
            new File(fileEvent.getDestinationDirectory()).mkdirs();
        }

        int filenamelength = dis.readInt();
        String filename = makeString(filenamelength, dis);

        dstFile = new File(path + filename);
        fileOutputStream = new FileOutputStream(dstFile);
        fileOutputStream.write(fileEvent.getFileData());
        fileOutputStream.flush();
        fileOutputStream.close();
        System.out.println("Output file : " + outputFile + " is successfully saved ");
        Thread.sleep(3000);
        System.exit(0);

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

这是将文件从客户端上传到服务器的客户端代码:

 public static void sendFile() throws Exception {
    dos.writeInt(6);
    dos.writeChars("upload");

    fileEvent = new FileEvent();
   String fileName = sourceFilePath.substring(sourceFilePath.lastIndexOf("/") + 1, sourceFilePath.length());
    String path = sourceFilePath.substring(0, sourceFilePath.lastIndexOf("/") + 1);
    fileEvent.setDestinationDirectory(destinationPath);
    fileEvent.setFilename(fileName);
    fileEvent.setSourceDirectory(sourceFilePath);
    File file = new File(sourceFilePath);
    if (file.isFile()) {
        try {
            DataInputStream diStream = new DataInputStream(new FileInputStream(file));
            long len = (int) file.length();
            byte[] fileBytes = new byte[(int) len];
            int read = 0;
            int numRead = 0;
            while (read < fileBytes.length && (numRead = diStream.read(fileBytes, read,
                    fileBytes.length - read)) >= 0) {
                read = read + numRead;
            }
            fileEvent.setFileSize(len);
            fileEvent.setFileData(fileBytes);
            fileEvent.setStatus("Success");
        } catch (Exception e) {
            e.printStackTrace();
            fileEvent.setStatus("Error");
        }
    } else {
        System.out.println("path specified is not pointing to a file");
        fileEvent.setStatus("Error");
    }
    //Now writing the FileEvent object to socket
    try {

        outputStream.writeObject(fileEvent);

        System.out.println("Choose file: ");
        String str = scanner.nextLine();

        String[] parts = str.split(Pattern.quote("\\"));
        String filename = parts[parts.length - 1];

        dos.writeInt(filename.length());
        dos.writeChars(filename);

        Thread.sleep(3000);
        System.exit(0);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

1 个答案:

答案 0 :(得分:0)

  1. 您没有说明您从哪个API获取FileEvent,但是您不应该使用任何假定该文件适合内存的技术:

    long len = (int) file.length();
    byte[] fileBytes = new byte[(int) len];
    

    在这里,您假设(a)len <= Integer.MAX_VALUE,以及(b)您可以创建该大小的字节数组。它没有扩展。

        int read = 0;
        int numRead = 0;
        while (read < fileBytes.length && (numRead = diStream.read(fileBytes, read,
                fileBytes.length - read)) >= 0) {
            read = read + numRead;
        }
        fileEvent.setFileSize(len);
        fileEvent.setFileData(fileBytes);
    

    同上。

  2. 你不应该在同一个套接字上混用ObjectOutputStreamDataOutputStream,如下所示:

    outputStream.writeObject(fileEvent);
    ...
    dos.writeInt(filename.length());
    dos.writeChars(filename);
    
  3. 所以,无论你的测试是什么,它都不会在一般情况下工作。

    相反,您应该使用现有的协议,如FTP,在下载时可以通过URL直接使用,在上传时可以通过Apache客户端使用。