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!

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

5 Comments

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..
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.
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
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!!
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.