鐢?FileWriter 鏉ュ啓鍏ユ枃浠剁殑甯哥敤鏂規硶鏄細 FileWriter fw = new FileWriter("mydata.txt"); PrintWriter out = new PrintWriter(fw); 鍦ㄧ敤out.print 鎴?out.println 鏉ュ線鏂囦歡涓啓鍏ユ暟鎹紝out.print 鍜?out.println鐨勫敮涓鍖哄埆鏄悗鑰呭啓 鍏ユ暟鎹垨浼氳嚜鍔ㄥ紑涓鏂拌銆傚啓瀹屽悗瑕佽寰?鐢╫ut.close() 鍏抽棴杈撳嚭錛岀敤fw.close() 鍏抽棴鏂囦歡銆?nbsp; 瀹屾暣浠g爜瑙?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(鈥渉i,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(); } } }