檔案的基本IO

Java 提供檔案基本套件都在java.io中,基本的管理檔案類別為 File 類別,可用來新增,刪除,檢查大小等等的功能,不過無法存取檔案內容,如下

   1:  package Test_IO;
   2:   
   3:  import java.io.*;//使用檔案套件必須先import套件類別
   4:   
   5:  public class Test_IO 
   6:  {
   7:   
   8:      /**
   9:       * @param args
  10:       * @throws IOException 
  11:       */
  12:      public static void main(String[] args) throws IOException{//建立檔案通常需要丟出 IOException
  13:          // TODO Auto-generated method stub
  14:          
  15:          /**建立目錄範例*/
  16:          File dir = new File("dirpath");//建立 file 物件(建立目錄用) 
  17:          dir.mkdirs();//建立目錄(預設位置在專案路徑下)
  18:          
  19:          /**建立檔案範例*/
  20:          File file = new File("filepath","Test_IO.txt");//建立 file 物件(建立檔案用)
  21:  //        file.createNewFile();//建立檔案 (執行錯誤,建立檔案若有指定目錄,必須先建立目錄再建立檔案
  22:          File filedir = new File("filepath");//先建立檔案的目錄的 file 物件
  23:          filedir.mkdirs();//建立檔案目錄
  24:          file.createNewFile();//建立檔案
  25:          
  26:          /**是否存在*/
  27:          if(dir.exists())
  28:          {
  29:              /**取得完整路徑*/
  30:              System.out.println(dir.getPath());// dirpath
  31:          }
  32:          
  33:          if(file.exists())
  34:          {
  35:              System.out.println(file.getPath());// file\Test_IO.txt
  36:              /**取得檔案大小*/
  37:              System.out.println(file.length());// 0
  38:              /**更改檔名*/
  39:              file.renameTo(new File(filedir,"Test_IO_2.txt"));
  40:              
  41:              //快速建立
  42:              new File(filedir,"Test_IO_3.txt").createNewFile();
  43:              
  44:              File tempfile = new File(filedir,"Test_IO_3.txt");
  45:              /**刪除檔案*/
  46:              tempfile.delete();
  47:          }
  48:      }
  49:   
  50:  }


想要存取檔案內容,必須先考慮檔案的格式,非文字檔使用 InputStream, OutputStream和其子類別,文字檔的話使用 Reader,Writer類別,如下

   1:  package Test_IO;
   2:   
   3:  import java.io.*;//使用檔案套件必須先import套件類別
   4:   
   5:  public class Test_IO_stream {
   6:   
   7:      /**
   8:       * @param args
   9:       */
  10:      public static void main(String[] args)throws IOException 
  11:      {
  12:          // TODO Auto-generated method stub
  13:          /**FileOutputStream範例*/
  14:          FileOutputStream fos = new FileOutputStream("testfos.txt");//建立文字檔
  15:          String tempstr = "good java no use?好爪哇不用嗎";
  16:          fos.write(tempstr.getBytes());//寫入
  17:          fos.close();
  18:          
  19:          
  20:          /**FileInputStream範例*/
  21:          FileInputStream fis = new FileInputStream(new File("testfos.txt")); 
  22:          for(int i2 =0; i2!=-1; i2 = fis.read())
  23:          {
  24:              System.out.print((char)i2);//good java no use??n???z??????
  25:          }
  26:          fis.close();
  27:          
  28:          System.out.println();
  29:          
  30:          /**FileWriter*/
  31:          FileWriter fw = new FileWriter("testwr.txt");
  32:          String tempstr2 = "好爪哇不用嗎 good java no use";
  33:          fw.write(tempstr2);
  34:          fw.close();
  35:          
  36:          
  37:          FileReader fr = new FileReader("testwr.txt");
  38:          for(int i=0; i!=-1;i = fr.read())
  39:          {
  40:              System.out.print((char)i);//好爪哇不用嗎 good java no use
  41:          }
  42:      }
  43:   
  44:  }

BufferedReader,BufferedWriter會在記憶體中製造緩衝區,等待資料充滿緩衝區後再一次處理,提高資料存取的效能,

   1:  package Test_IO;
   2:   
   3:  import java.io.*;
   4:   
   5:  public class Test_BufferedReader {
   6:   
   7:      /**
   8:       * @param args
   9:       */
  10:      public static void main(String[] args) throws IOException
  11:      {
  12:          // TODO Auto-generated method stub
  13:          
  14:          /**BufferedWriter , BufferedOutputStream範例*/
  15:          FileWriter fw = new FileWriter("testfw2.txt");
  16:          FileOutputStream fos = new FileOutputStream("testfos2");
  17:          //BufferedWriter bw = new BufferedWriter(fos); 錯誤 BufferedWriter 對應 FileWriter,不可使用在OutputStream上
  18:          BufferedWriter bw = new BufferedWriter(fw);//傳入參數為FileWriter
  19:          BufferedOutputStream bos = new BufferedOutputStream(fos);//傳入參數為FileOutputStream
  20:          
  21:          String temps1 = "好爪哇不用嗎";
  22:          String temps2 = "fweuhf3urhhf";
  23:          
  24:          //寫入
  25:          bw.write(temps1);
  26:          bw.close();
  27:          fw.close();
  28:          
  29:          //寫入
  30:          bos.write(temps2.getBytes());
  31:          bos.close();
  32:          fos.close();
  33:          
  34:          /**BufferedInputStream 範例*/
  35:          FileInputStream fis = new FileInputStream("testfos2");
  36:          BufferedInputStream bis = new BufferedInputStream(fis);
  37:          int i = 0;
  38:          while((i = bis.read())!=-1)
  39:          {
  40:              System.out.print((char)i);
  41:          }        
  42:          bis.close();
  43:          fis.close();
  44:          
  45:          System.out.println();
  46:          
  47:          /**BufferedReader 範例*/
  48:          FileReader fr = new FileReader("testfw2.txt");
  49:          BufferedReader br = new BufferedReader(fr);
  50:          String stemp1 = "";
  51:          stemp1 = br.readLine();
  52:          System.out.println(stemp1);
br.close();
fr.close();
  53:      }
  54:   
  55:  }

也能把類別物件寫入檔案中,ObjectInputStream , ObjectOutputStream 可達到這個要求,必須注意要寫入檔案的類別必須實作 serializable 介面以序列化

   1:  package Test_IO;
   2:   
   3:  import java.io.*;
   4:   
   5:  public class Test_ObjectStream {
   6:   
   7:      /**
   8:       * @param args
   9:       */
  10:      public static void main(String[] args) throws Exception 
  11:      {
  12:          
  13:          //ObjectOutputStream 範例
  14:          FileOutputStream fos = new FileOutputStream("testObject");
  15:          ObjectOutputStream oos = new ObjectOutputStream(fos);
  16:          
  17:          for(int i =0; i<10; i++)
  18:          {
  19:              //寫入 object
  20:              oos.writeObject(new TestClass());
  21:          }
  22:          
  23:          oos.close();
  24:          fos.close();
  25:          
  26:          
  27:          ObjectInputStream ois = new ObjectInputStream(new FileInputStream("testObject"));
  28:          
  29:          //取出方法
  30:          while(1==1)
  31:          {
  32:              try{
  33:                  
  34:              ((TestClass)ois.readObject()).showtcNum();
  35:              
  36:              }
  37:              catch(EOFException eofe)
  38:              {
  39:  //                eofe.printStackTrace();
  40:              }
  41:          }
  42:   
  43:          
  44:          
  45:      }
  46:   
  47:  }
  48:   
  49:  class TestClass implements Serializable //序列化 ,物件必須實作 serializable
  50:  {
  51:      int tcNum1;
  52:      String tcStr1;
  53:      
  54:      static int tcTotalCount;
  55:      
  56:      TestClass()
  57:      {
  58:           this.tcNum1 = tcTotalCount;
  59:           tcTotalCount++;
  60:      }
  61:      
  62:      public void showtcNum()
  63:      {
  64:          System.out.println(tcNum1);
  65:      }
  66:  }