Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

How to read & write with DataInputStream & DataOutputStream?

807601Apr 27 2008 — edited Apr 28 2008
Hi,
I am trying to write a simple FTP-eque client and server (an assignment) and am confused about how to read and write from DataInputStreams and DataOutputStreams. So to try to understand these better I wrote a little program to simple read a file with a DataInputStream and then write it to a new file with a DataOutputStream. Since the file may not be text based I thought it best to use the write() and read() methods rather than something like writeBytes(). I figure that the read-write should go like this:
- read a given number of bytes from the old file with DataInputStream, store in a byte array
- write the bytes in that array to a new file with DataOutputStream
- continue until the end of the old file

I would really appreciate some insight on how to 'correctly' handle chaining these streams, and/or an example of how to do so.

My code:
import java.io.*;
import java.net.*;

public class FileIn {

	public static void main (String args[]) throws Exception {
	
		String file = "/home/craig/oldfile.txt";
		String newfile = "/home/craig/newfile.txt";
		File f1 = new File(file);
		File f2 = new File(newfile);

		DataInputStream din = null;
		DataOutputStream dout = null;
		din = new DataInputStream( new FileInputStream(f1) );
		dout = new DataOutputStream( new FileOutputStream(f2) );

		int len = 1024;
		byte[] buf = new byte[len];
		byte[] b = null;
		
		while ( (b = din.read(buf)) != null ) {
			dout.write(b); 
		}
		dout.flush();
		dout.close();
	}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 26 2008
Added on Apr 27 2008
4 comments
1,427 views