ç”?FileWriter æ¥å†™å…¥æ–‡ä»¶çš„常用æ–ÒŽ³•是: FileWriter fw = new FileWriter("mydata.txt"); PrintWriter out = new PrintWriter(fw); 在用out.print æˆ?out.println æ¥å¾€æ–‡äšgä¸å†™å…¥æ•°æ®ï¼Œout.print å’?out.println的唯一区别是åŽè€…写 å…¥æ•°æ®æˆ–会自动开一新行。写完åŽè¦è®°å¾?用out.close() å…³é—输出åQŒç”¨fw.close() 关闿–‡äšgã€?nbsp; 完整代ç è§?Example 4ã€?BR> -------------------------------------------------------------- following is the source code of examples------------------------------------------------------
Example 1: // FileInputDemo // Demonstrates FileInputStream and DataInputStream import java.io.*; class FileInputDemo { publicstaticvoid main(String args[]) { // args.length is equivalent to argc in C if (args.length ==1) { try{ // Open the file that is the first command line parameter FileInputStream fstream =new FileInputStream(args[0]); // Convert our input stream to a DataInputStream DataInputStream in=new DataInputStream(fstream); // Continue to read lines while there are still some left to read while (in.available() !=0) { // Print file line to screen System.out.println (in.readLine()); } in.close(); }catch (Exception e) { System.err.println("File input error"); } } else System.out.println("Invalid parameters"); } }
Example 2:
// FileOutputDemo // Demonstration of FileOutputStream and PrintStream classes import java.io.*; class FileOutputDemo { publicstaticvoid main(String args[]) { FileOutputStream out; // declare a file output object PrintStream p; // declare a print stream object try{ // connected to "myfile.txt" out=new FileOutputStream("myfile.txt"); // Connect print stream to the output stream p =new PrintStream( out ); p.println ("This is written to a file"); p.close(); }catch (Exception e) { System.err.println ("Error writing to file"); } } }
Example 3:
// FileReadTest.java // User FileReader in JDK1.1 to read a file import java.io.*; class FileReadTest { publicstaticvoid main (String[] args) { FileReadTest t =new FileReadTest(); t.readMyFile(); } void readMyFile() { String record =null; int recCount =0; try{ FileReader fr =new FileReader("mydata.txt"); BufferedReader br =new BufferedReader(fr); record =new String(); while ((record = br.readLine()) !=null) { recCount++; System.out.println(recCount +": "+ record); } br.close(); fr.close(); }catch (IOException e) { System.out.println("Uh oh, got an IOException error!"); e.printStackTrace(); } } }
Example 4:
// FileWriteTest.java // User FileWriter in JDK1.1 to writer a file import java.io.*; class FileWriteTest { publicstaticvoid main (String[] args) { FileWriteTest t =new FileWriteTest(); t.WriteMyFile(); } void WriteMyFile() { try{ FileWriter fw =new FileWriter("mydata.txt"); PrintWriter out=new PrintWriter(fw); out.print(“hi,this will be wirte into the file!�; out.close(); fw.close(); }catch (IOException e) { System.out.println("Uh oh, got an IOException error!"); e.printStackTrace(); } } }