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();
}
}