简体   繁体   中英

Download file from server to client using socket in java

I got some code to upload file from client to server and that working fine, the uploaded file saved in Server folder called Server, now would like to download file that exist in server folder to client folder but do not know how to do that. please give help

this server code illustrate downloading file from client to 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();
    }
}

and this is the client code to upload file from client to server:

 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. You don't state which API you're getting FileEvent from, but you shouldn't be using any technique like this that assumes the file will fit into memory:

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

    Here you're assuming (a) that len <= Integer.MAX_VALUE , and (b) that you can create a byte array of that size. It doesn't scale.

      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); 

    Ditto.

  2. You shouldn't mix use of ObjectOutputStream and DataOutputStream on the same socket like this:

     outputStream.writeObject(fileEvent); ... dos.writeInt(filename.length()); dos.writeChars(filename); 

So already it isn't going to work in the general case, whatever your tests may show.

Instead you should either use an existing protocol like FTP, which you can use directly via a URL in the case of downloading, and via the Apache client in the case of uploading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM