// this program copies a file from args[0] to args[1] // it illustrates both binary and text io in java. import java.io.*; public class filecopy { public static final int BUFSIZE = 1024; public static void main(String[] args) // args contain src, dest { int n; // number of bytes succesfully read try { // file channels FileInputStream fin = new FileInputStream(args[0]); FileOutputStream fout = new FileOutputStream(args[1]); // binary io through channel: DataInputStream din = new DataInputStream(fin); DataOutputStream dout = new DataOutputStream(fout); // copy buffer byte[] buffer = new byte[BUFSIZE]; // copy loop n = buffer.length; while (n>0) { n = din.read(buffer,0,buffer.length); if (n>0) dout.write(buffer,0,n); // technically, write also writes UP TO n bytes, but // it's unlikely to be less than n for local files. } din.close(); dout.close(); } catch (IOException e) {e.printStackTrace();} } // main // the following version uses buffered streams, but can only // copy ascii files. public static void main2(String[] args) { try { FileInputStream fin = new FileInputStream(args[0]); FileOutputStream fout = new FileOutputStream(args[1]); BufferedReader br = new BufferedReader(new InputStreamReader(fin)); PrintWriter pw = new PrintWriter(new OutputStreamWriter(fout)); String sin = "blah"; // input string; while (sin != null) { sin = br.readLine(); // sin doesn't include the \n if (sin!=null) pw.println(sin); // sin==null at eof } br.close(); pw.close(); } catch (IOException e) {e.printStackTrace();} } // main2 } // filecopy