问题
I am trying to build a client that sends the file size and contents to server.
I am trying to use DataOutputStream.
I am assuming that I need to open the file and and get size of file and read the contents and send it.
But I am not sure how to implement those because I am really new to java...
Can anyone help me about this?
Thank you!
回答1:
It's quite simple, but the code is a bit long to write it all and sounds like homework.
I can give you some indications.
Just open the file, use the long length()
method of the class File
to get the size, and the writeLong(long)
method of DataOutputStream
to send the length to the server. Then just read the file a block at a time and use the write(byte[])
method of DataOutputStream
to send each block.
To read a file a block at a time, you will just create a FileInputStream
and use its int read(byte[])
method. Be careful not to assume that this metod will fill up the whole buffer, because it is not guaranteed to do. Read the docs!
来源:https://stackoverflow.com/questions/7616776/sending-a-file-using-dataoutputstream-in-java