File類--輸入流和輸出流

建立文件對象:能夠是物理文件或目錄,操做文件或目錄的屬性(路徑、權限、日期和時間等)java

經過流來讀寫文件,流是一組有序的數據序列,以先進先出方式發送信息的通道數組

不少的信息,都是經過文件來讀取的,文件是數據源緩存

對於程序來講,把文件讀入到程序中,這是輸入,把資料讀出去是是輸出。app

在Java中流的分類:測試

按流向區分:        一、輸出流---->OutputStream和Writer做爲基類編碼

              二、輸入流---->InputputStream和Reader做爲基類                    輸入輸出流是相對於計算機內存來講的spa

 

按照處理數據單元劃分:    一、字節流---->字節輸入流InputputStream  字節輸出流OutputStream這兩個做爲基類  字節流是8位經過字節流,字符流是16位Unicode字符流code

               二、字符流---->字符輸入流Reader       字符輸出流Writer這兩個做爲基類 視頻

一般使用按處理數據單元劃分的多一點。對象

字節流:  InputStream

            read()            從輸入流一個字節一個字節的讀,返回的是該字節的整數表示形式,若是到了輸入流的末尾,返回-1

            read(byte[ ] a)         從輸入流讀取若干字節,把這些字節保存到數組a中,返回的是讀取到字節數,若是到了輸入流的末尾,返回-1

            read(byte[ ] a,int off,int len)    從輸入流讀取若干字節,把這些字節保存到數組a中,off指的是字節數組中開始保存數據的起始下標,len指讀取的字節數                                                                                                     目。返回的是讀取到的字節數,若是到了輸入流的末尾,返回-1

            close()

            available()  能夠從輸入流中讀取的字節數目

      FileInputStream(子類FileInputStream經常使用的構造方法)

            new FileInputStream(File file)    這是一個文件類

            new FileInputStream(String path)   這是路徑

      OutputStream

            write(int a)

            write(byte [ ] a)

            write(byte [ ] a,int off ,int len)

            close()

            flush()              強制將緩衝區清空

      FileOutputStream

            new FileOutputStream(File file)

            new FileOutputStream(String path)

            new FileOutputStream(String path,boolean append)能夠指定覆蓋或追加文件內容,設置爲true的時候,就是追加

       Reader

            read()            從輸入流一個字節一個字節的讀,返回的是該字節的整數表示形式,若是到了輸入流的末尾,返回-1

            read(byte[ ] a)         從輸入流讀取若干字節,把這些字節保存到數組a中,返回的是讀取到字節數,若是到了輸入流的末尾,返回-1

            read(byte[ ] a,int off,int len)    從輸入流讀取若干字節,把這些字節保存到數組a中,off指的是字節數組中開始保存數據的起始下標,len指讀取的字節數                                                                                                     目。返回的是讀取到的字節數,若是到了輸入流的末尾,返回-1

            close()

       InputStreamReader(是Reader的子類)能夠指定字符編碼格式

            new InputStreamReader(InputStream in)

            new InputStreamReader(InputStream in, String charsetName)  String charsetName這就是想要的編碼格式,流和文件是編碼格式化要一致,好比文件                                                                                                                                                       格式是GBK,而後設置的也要是GBK

      FileInputStreamReader(是InputStreamReader的子類,該類只能按照本地平臺的字符編碼來讀取數據,用戶不能指定其餘的字符編碼類型)

            new FileReader(File file)

            new FileReader(String name)

中文亂碼:  緣由:文件編碼格式  和程序環境的編碼格式不一致謝

       解決方案:FileReader是沒法指定編碼格式的,會按照程序的編碼格式打印的。可使用InputStreamReader字符輸入流 

BufferedReader      緩衝區輸入流類,再將Reader類包裝成BufferedReader類,爲了提升效率,把文件內容都讀到了緩衝區中,而後讀取數據的時候,就直接在緩衝區區讀取

        readLine()  這個方法,一次將一行的內容讀取出來    

        System.getProperty("file.encoding");得到本地平臺的字符編碼類型

        Writer

            writer(String str)        將str字符串裏包含的字符輸出到指定的輸出流中

            writer(String str,int off,int len)   將str字符串裏從off位置開始,長度爲len的多個字符輸出到輸出流中

            close()

            flush()            刷新輸出流,清空緩存

     OutputStreamWriter(是Writer的子類)

            OutputStreamWriter(OutputStream out)

            OutputStreamWriter(OutputStream out,String charsetName)

     BufferedWriter

Writer中也有輸出的字符的緩衝區輸出流,注意緩衝區的內容是字符串了,再也不是字節了

緩衝區其實就是一個字節數組,它要積累的必定的數量,纔會輸入或輸出

注意:全部的流都要關了,輸出流不只要關流,還要清空緩衝區的數據

二進制流:就是進行圖片、音樂等這樣的文件,就是使用二進制流進行讀寫的

    DataInputStream:是FileInputStream的子類,與FileInputStream結合使用,使用的方法跟InputStream方法同樣

            new DataInputStream (InputStream in)

    DataOutputStream:是FileOutputStream的子類,與FileOutputStream結合使用

            new DataOutputStream(OutputStream in)

序列化與反序列化:序列化就是將對象(Java中建立的對象)的狀態寫入到特定的流中的位置,記得對象所屬的類能夠完成序列化,要完成序列化的對象,要記得去實現序列化的接口Serializable,才能夠進行序列化的操做,對象中的某一個狀態不想被序列化,能夠在相應的屬性中加一個關鍵字transient。

         序列化,就是把對象放進到流中,這個使用的是ObjectOutputStream,反之則使用ObjectInputStream

    ObjectInputStream

            new ObjectInputStream(FileInputStream fis)     注意:由於是Object對象,因此使用的方法跟InputStream同樣,只是是readObject()方法

    ObjectOutputStream

            new ObjectOutputStream(FileOutputStream fis)  注意:反序列化接收到的是Object對象,因此要進行類型轉換,使用的方法也是writerObject()方法

使用io的步驟:

  一、引入相關的類

  二、構造文件輸入流或輸出流或字符輸入流或字符輸出流

  三、讀取或寫出文本文件的數據

  四、關閉流對象

案例1:普通的輸入和輸出

import java.io.File;

import java.io.IOException;

public class TestClass {

   /**  

  * 建立一個文件或者目錄  

  * @param file  

   */  

  public void creatFile(File file){  

     if(file.exists()){//判斷文件或目錄是否存在,存在爲true    

      System.out.println("此文件已存在!");   

    }else{   

      try {    

         file.createNewFile();//建立文件     

        System.out.println("文件建立成功!");    

      } catch (IOException e) {     

        e.printStackTrace();   

       }   

    }

   }  

  /**  

  * 得到文件的信息  

  * @param file  

  */ 

  public void getFileInfo(File file){   

    if(file.exists()){//先判斷是否有此文件或者目錄   

       if(file.isFile()){//判斷是不是文件    

         //得到文件的絕對路徑     

        String string=file.getPath();//相對路徑     

        String a=file.getAbsolutePath();//絕對路徑     

        String name=file.getName();//得到文件名     

        System.out.println("相對路徑:\t"+string);     

        System.out.println("絕對路徑:\t"+a);     

        System.out.println("文件名爲:"+name);    

        System.out.println("文件大小爲:"+file.length());   

     }    

      if(file.isDirectory()){//判斷是不是目錄     

        System.out.println("此文件是目錄");    

      }   

    }else {    

      System.out.println("此文件不存在!");   

    }  

  }  

  /**  

  * 刪除文件  

  * @param file  

  */  

  public void del(File file){   

    if(file.exists()){//先要判斷是否有此文件才能夠進行刪除工做    

      file.delete();    

      System.out.println("刪除文件成功!");   

    }else{    

      System.out.println("此文件不存在");   

    }  

  }  

}

public static void main(String[] args) {
    //要去判斷是否有這個文件或者目錄,若是沒有,那麼就去建立一個文件
    TestClass testClass=new TestClass();
    File file=new File("E:/練習/text.txt");//這裏是要建立的文件
  //  testClass.creatFile(file);//經過調用方法去檢查是否有該文件或目錄,沒有就建立
  //  testClass.getFileInfo(file);
    testClass.del(file);
 }

案例2:輸入流和輸出流的結合使用

public static void main(String[] args) {

  //出現的問題:1:前面有一堆的字符,而後輸入的中文有亂碼的問題,解決的方法是FileOutputStream的write方法中,結束的位置是data,不是數組的長度
  //先把要複製的文件輸入出來,而後再輸出文件出來
  //建立輸入流
  FileOutputStream fos=null;
  //建立輸出流
  FileInputStream fis=null;
  try {
   //須要複製的原文件
   fis=new FileInputStream("E:/練習/test.txt");
   //複製到的文件,內容進行追加
   fos=new FileOutputStream("E:/練習/text.txt",true);
   //讀取的長度
   int data=-1;
   //建立一個數組,去接收文件
   byte [] b=new byte[1024];
   try {
    //經過讀取去得到文件內容
    while ((data=fis.read(b))!=-1) {
     //經過輸出流將文件寫到目標文件中去,長度是讀取到的文件內容的長度
     fos.write(b, 0, data);
    }

  /*//這裏在循環條件中讀取了一次,而後在循環體中又讀取了一次,因此讀取出來的文件內容是沒有第一個字節的
    while((fis.read())!=-1){
     fis.read(b);
     //這裏結束的尾部是數組的長度,若是數組沒有讀取出那麼多,就會在文件中尾部輸出不少的空格,因此這裏要是文件的長度
     fos.write(b,0,b.length);
    }*/
    System.out.println("複製成功!");
   } catch (IOException e) {
    e.printStackTrace();
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
 }

案例3:全部文件的輸入和輸出流的結合使用

public static void main(String[] args) {
  InputStream is=null;//輸入流
  InputStreamReader isr=null;
  BufferedInputStream bis=null;
  
  OutputStream os=null;//輸出流
  OutputStreamWriter osw=null;
  BufferedOutputStream bos=null;
  try {
   //建立出輸入流
   is=new FileInputStream("F:/劉楠梅/hello.txt");
   bis=new BufferedInputStream(is);
   isr=new InputStreamReader(is,"GBK");//由於txt文件默認的編碼格式是GBK,因此輸入流設置的編碼格式也要是GBK
   
   //建立輸出流
   os=new FileOutputStream("G:/測試/你好.txt",true);
   bos=new BufferedOutputStream(os);
   osw=new OutputStreamWriter(os,"GBK");
   //設置接收讀取的長度
   int len=-1;
   //讀取的字符數組
   byte [] b=new byte[1024];
   //循環遍歷文件的內容,當內容爲-1的時候,跳出循環
   while((len=bis.read(b))!=-1){
    //將文件輸出
    bos.write(b);
   }
   //要將輸出流強制清空,否則文件不會有內容
   bos.flush();
   System.out.println("完成複製!");
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   try {
    //最後關閉全部使用的流,記得後的先關閉,最早的最後關閉
    osw.close();
    bos.close();
    os.close();
    isr.close();
    bis.close();
    is.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }

案例4:這是一個字符流的輸入

public static void main(String[] args) {
  Reader reader=null;
  try {
   reader=new FileReader("E:/練習/text.txt");
   int data=-1;
   //讀取的再也不是字節了,而是字符了,因此使用char數組去接收讀取出來的內容
   char []b=new char[1024];
   //可使用StringBuffer類去添加字符串,會比較靈活
   StringBuffer stringBuffer=new StringBuffer();
   try {
    //data是實際讀取到的字符數
    while ((data=reader.read(b))!=-1) {
     stringBuffer.append(b);
    }
    System.out.println(stringBuffer);
   } catch (IOException e) {
    e.printStackTrace();
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }finally{

//記得必定要關閉流
   try {
    reader.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }

案例5:二進制輸入流和輸了流的結合使用

public static void main(String[] args) {
  DataInputStream dis=null;
  FileInputStream fis=null;
  DataOutputStream dos=null;
  FileOutputStream fos=null;
  BufferedInputStream bis=null;
  BufferedOutputStream bos=null;
  try {
   fis=new FileInputStream("G:/圖/IMG_0054.JPG");//地址
   dis=new DataInputStream(fis);
   bis=new BufferedInputStream(fis);
   fos=new FileOutputStream("E:/視頻/myphote.JPG");
   dos=new DataOutputStream(fos);
   bos=new BufferedOutputStream(fos);
   byte [] b=new byte[1024];
   int len=-1;
   while((len=bis.read(b))!=-1){
    bos.write(b);
   }
   System.out.println("寫完");
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   try {
    bos.close();
    dos.close();
    fos.close();
    bis.close();
    dis.close();
    fis.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }

案例6:序列化與反序列化

public static void main(String[] args) {  Student stu=new Student("小紅",18,"123456");  InputStream is=null;  ObjectInputStream ois=null;  //這是序列化,是把對象寫進流中,是輸出  OutputStream os=null;  ObjectOutputStream oos=null;  try {   //序列化   os=new FileOutputStream("G:/測試/hello.txt");//輸出流   oos=new ObjectOutputStream(os);   oos.writeObject(stu);//傳入的參數是Object類型   os.flush();   is=new FileInputStream("G:/測試/hello.txt");//輸入流   ois=new ObjectInputStream(is);   Student s=(Student)ois.readObject();   System.out.println(s.getName()+"\t"+s.getAge()+"\t"+s.getPassword());  } catch (FileNotFoundException e) {   e.printStackTrace();  } catch (IOException e) {   e.printStackTrace();  } catch (ClassNotFoundException e) {   e.printStackTrace();  }finally{   try {    ois.close();    is.close();    oos.close();    os.close();   } catch (IOException e) {    e.printStackTrace();   }  }   }

相關文章
相關標籤/搜索