Sending file through ObjectOutputStream and then saving it in Java?

前端 未结 2 570
渐次进展
渐次进展 2021-01-06 07:35

I have this simple Server/Client application. I\'m trying to get the Server to send a file through an OutputStream (FileOutputStream, OutputStream, ObjectOutputStream, etc)

相关标签:
2条回答
  • 2021-01-06 07:56

    A File object represents the path to that file, not its actual content. What you should do is read the bytes from that file and send those over your ObjectOutputStream.

    File f = ...
    ObjectOutputStream oos = ...
    
    byte[] content = Files.readAllBytes(f.toPath);
    oos.writeObject(content);
    


    File f=...
    ObjectInputStream ois = ...
    
    byte[] content = (byte[]) ois.readObject();
    Files.write(f.toPath(), content);
    
    0 讨论(0)
  • 2021-01-06 07:57

    You are not actually transferring the file, but the File instance from Java. Think of your File object as a (server-)local handle to the file, but not its contents. For transferring the image, you'd actually have to read it on the server first.

    However, if you're just going to save the bytes on the client anyway, you can forget about the ObjectOutputStream to begin with. You can just transfer the bytes stored in the File. Take a look at the FileChannel class and its transferTo and transferFrom methods as a start.

    0 讨论(0)
提交回复
热议问题