2

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!

in His Steps
  • 3,075
  • 6
  • 30
  • 38

1 Answers1

4

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!

gd1
  • 11,300
  • 7
  • 49
  • 88
  • I see. Do you need to specified the path before open the file? for ex. File file = new File(filename), does filename need to have the path? because every time I tried to do that, it doesn't open.. – in His Steps Sep 30 '11 at 22:48
  • It depends. If you don't specify the full path, then it'll search the file starting from the CWD (current working directory) which is in most cases the directory you are currently working with your terminal when you run the `java` command line application. The directory of the .jar or the .class files is not relevant, but *might* be the same of the CWD. – gd1 Sep 30 '11 at 22:51
  • I am actually compiling and running through eclipse. and the file I want to open is in same directory as .java files I am writing. They are in /src directory. in fact all the .class files go to different directory called /bin. I assume the file should be in current directory right? or am I wrong? Thank you very much for your help – in His Steps Sep 30 '11 at 22:57
  • The working directory is the parent of both `src` and `bin`. Suggestion: AVOID environments like Eclipse until you're skilled with the command line tools, and with the language itself. Need to learn some basics :) Sorry to tell!! – gd1 Sep 30 '11 at 22:57
  • If you feel this solved your issue, please 'accept' my answer clicking on the green bordered tick at the left. It will also help you increase your 'accept' rate. Thank you. – gd1 Oct 03 '11 at 08:19