1 Read file characters and print:
public class Demo01 { /** * @param args */ public static void main(String[] args) { //create source File src =new File("E:/xp/test/a.txt"); // select stream Reader reader =null; try { reader =new FileReader(src); // read operation char[] flush =new char[1024]; int len = 0; while(-1!=(len=reader.read(flush))){ // // convert character array to string String str =new String(flush,0,len); System.out.println(str); } } catch (FileNotFoundException e) { e.printStackTrace (); System.out.println("The source file does not exist"); } catch (IOException e) { e.printStackTrace (); System.out.println("Failed to read file"); }finally{ try { if (null != reader) { reader.close(); } } catch (Exception e2) { } } } }
2 file copies:
public class CopyFileDemo { /** * @param args */ public static void main(String[] args) { //Create plain text whose source is limited to characters File src =new File("E:/xp/test/Demo03.java"); File dest =new File("e:/xp/test/char.txt"); // select stream Reader reader =null; Writer wr =null; try { reader =new FileReader(src); wr =new FileWriter(dest); // read operation char[] flush =new char[1024]; int len = 0; while(-1!=(len=reader.read(flush))){ // Note, read the data into the flush container wr.write(flush, 0, len); } wr.flush();//Force flush out } catch (FileNotFoundException e) { e.printStackTrace (); System.out.println("The source file does not exist"); } catch (IOException e) { e.printStackTrace (); System.out.println("Failed to read file"); }finally{ try { if (null != wr) { wr.close(); } } catch (Exception e2) { } try { if (null != reader) { reader.close(); } } catch (Exception e2) { } } } }