1. 程式人生 > >8、IO技術

8、IO技術

8. IO技術

1. File類

File(掌握)

1、IO流操作中大部分都是對檔案的操作,所以Java就提供了File類供我們來操作檔案

2、構造方法

A:File file = new File("e:\\demo\\a.txt");

B:File file = new File("e:\\demo","a.txt");

C:File file = new File("e:\\demo");

  File file2 = new File(file,"a.txt");

3、File類的功能

(1)、檔名

getName() 檔名、路徑名,返回名稱

getPath()路徑名,如果是絕對路徑,返回完整路徑,否則相對路徑

getAbsoluteFile() 絕對路徑所對應的File物件

getAbsolutePath() 絕對路徑名

getParent() 父目錄 ,相對路徑的父目錄,可能為null 如刪除本身後的結果

(2)、判斷資訊

exists()   canWrite()  canRead()  isFile()  isDirectory()

isAbsolute():消除平臺差異,ie以碟符開頭,其他以/開頭

(3)、長度 位元組數  不能讀取資料夾的長度length()

(4)、建立、刪除

createNewFile() 不存在建立新檔案,存在返回false,建立檔名時含有con系統關鍵字,則建立失敗

delete() 刪除檔案

static createTempFile(字首3個位元組長,字尾預設.temp) 預設臨時空間

staticcreateTempFile(字首3個位元組長,字尾預設.temp,目錄)

deleteOnExit() 退出虛擬機器刪除,常用於刪除臨時檔案

(5)、操作目錄

mkdir() 建立目錄,必須確保父目錄存在,如果不存在,建立失敗

mkdirs() 建立目錄,如果父目錄鏈不存在一同建立

list() 返回檔案|目錄 名字串形式

listFiles()

static listRoots() 根路徑

 

/**

 * 兩個常量

 * 1、路徑分隔符  ;

 * 2、名稱分隔符 /(windows)  /(linux )

 */

public class Demo01 {

   public static void main(String[] args) {

      System.out.println(File.pathSeparator);

      System.out.println(File.separator);

      //路徑表示形式

      String path ="E:\\xp\\test\\2.jpg";

   path="E:"+File.separator+"xp"+File.separator+"test"+File.separator+"2.jpg";

      //推薦方式

      path="E:/xp/test/2.jpg";

   }

 

}

 

/**

 * 相對路徑與絕對路徑構造 File物件

 * 1、相對路徑

    File(String parent, String child)  ==>File("E:/xp/test","2.jpg")

    File(File parent, String child)     ==> File(new File("E:/xp/test"),"2.jpg")

    2、絕對路徑

    File(String name);

 * @author Administrator

 *

 */

public class Demo02 {

 

   /**

    * @param args

    */

   public static void main(String[] args) {

      String parentPath ="E:/xp/test";

      String name ="2.jpg";

      //相對路徑

      File src =new File(parentPath,name);

      src =new File(new File(parentPath),name);

      //輸出

      System.out.println(src.getName());

      System.out.println(src.getPath());

      //絕對路徑

      src =new File("E:/xp/test/2.jpg");

      System.out.println(src.getName());

      System.out.println(src.getPath());

      //沒有碟符: user.dir構建

      src =new File("test.txt");

      src =new File(".");

      System.out.println(src.getName());

      System.out.println(src.getPath());

      System.out.println(src.getAbsolutePath());

   }

 

}

 

/**

 * 常用方法:

1、檔名

getName() 檔名、路徑名

getPath()路徑名

getAbsoluteFile() 絕對路徑所對應的File物件

getAbsolutePath() 絕對路徑名

getParent() 父目錄 ,相對路徑的父目錄,可能為null . 刪除本身後的結果

2、判斷資訊

exists()

canWrite()

canRead()

isFile()

isDirectory()

isAbsolute():消除平臺差異,ie以碟符開頭,其他以/開頭

3、長度 位元組數  不能讀取資料夾的長度

length()

4、建立、刪除

createNewFile() 不存在建立新檔案,存在返回false

delete() 刪除檔案

static createTempFile(字首3個位元組長,字尾預設.temp) 預設臨時空間

staticcreateTempFile(字首3個位元組長,字尾預設.temp,目錄)

deleteOnExit() 退出虛擬機器刪除,常用於刪除臨時檔案

 

 

 * @author Administrator

 *

 */

public class Demo03 {

 

   /**

    * @param args

    */

   public static void main(String[] args) {

      test2();

      try {

        test3();

      } catch (IOException e) {

        e.printStackTrace();

        System.out.println("檔案操作失敗");

      } catch (InterruptedException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

      }

  

   }

   //建立刪除檔案

   public static void test3() throws IOException, InterruptedException{

      //createNewFile() 不存在建立新檔案

      //String path="E:/xp/test/con"; //con系統關鍵字

      String path="E:/xp/test/200.jpg";

      //String path="E:/xp/test/1.jpg";

      File src =new File(path);

      if(!src.exists()){

        boolean flag =src.createNewFile();

        System.out.println(flag?"成功":"失敗");

      }

     

      //刪除檔案

      boolean flag =src.delete();

      System.out.println(flag?"成功":"失敗");

     

     

      //static createTempFile(字首3個位元組長字尾預設.temp) 預設臨時空間

      //static createTempFile(字首3個位元組長字尾預設.temp,目錄)

      File temp= File.createTempFile("tes", ".temp",new File("e:/xp/test"));     

      Thread.sleep(10000);    

      temp.deleteOnExit(); //退出即刪除

     

   }

  

  

 

   //2、判斷資訊

   //3、長度 length()

   public static void test2(){

      //String path ="2.txt";

      String path="E:/xp/test/200.jpg";

      //String path="E:/xp/test/200.jpg";

      File src =new File(path);

      //是否存在

      System.out.println("檔案是否存在:"+src.exists());

      //是否可讀 canWrite() canRead()

      System.out.println("檔案是否可寫"+src.canWrite());

      System.out.println("============");

      //isFile()

      //isDirectory()

      if(src.isFile()){

        System.out.println("檔案");

      }else if(src.isDirectory()){       

        System.out.println("資料夾");

      }else{

        System.out.println("檔案不存在");

      }

     

      System.out.println("是否為絕對路徑"+src.isAbsolute());

      System.out.println("長度為:"+src.length());

     

   }

   //1、名稱

   public static void test1(){

      //File src =new File("E:/xp/test/2.jpg");

      //建立聯絡

      File src =new File("2.txt");

      System.out.println(src.getName()); //返回名稱

      System.out.println(src.getPath()); //如果是絕對路徑返回完整路徑否則相對路徑

      System.out.println(src.getAbsolutePath());//返回絕對路徑

      System.out.println(src.getParent());//返回上一級目錄,如果是相對,返回null

   }

 

}

 

/**

 * 5、操作目錄

mkdir() 建立目錄,必須確保 父目錄存在,如果不存在,建立失敗

mkdirs() 建立目錄,如果父目錄鏈不存在一同建立

list() 檔案|目錄 名字串形式

listFiles()

static listRoots() 根路徑

 * @author Administrator

 *

 */

public class Demo04 {

 

   /**

    * @param args

    */

   public static void main(String[] args) {

      String path ="E:/xp/test/";

      File src =new File(path); //資料夾

      if(src.isDirectory()){ //存在並且為目錄

        System.out.println("======子目錄|檔名===");

        String[] subNames =src.list();

       

        for(String temp:subNames){

           System.out.println(temp);

        }

        System.out.println("=====子目錄|檔案File物件====");

        File[] subFiles =src.listFiles();

        for(File temp:subFiles){

           System.out.println(temp.getAbsolutePath());

        }

        System.out.println("=====子檔案.java物件====");

        //命令設計模式

        subFiles =src.listFiles(new FilenameFilter(){

             

           @Override

           /**

            * dir 代表src

            */

           public boolean accept(File dir, String name) {

              //System.out.println(dir.getAbsolutePath());

              return  new File(dir,name).isFile()&&name.endsWith(".java");

           }

          

        });

        for(File temp:subFiles){

           System.out.println(temp.getAbsolutePath());

        }

       

       

      }

   }

   public static void test1(){

      String path ="E:/xp/test/parent/p/test";

      File src =new File(path);

      //src.mkdir();

      src.mkdirs();

   }

 

}

 

/**

 * 輸出子孫級目錄|檔案的名稱(絕對路徑)

 * 1listFiles()

 * 2、遞迴

 *

 * static listRoots() 根路徑

 *

 */

public class Demo05 {

 

   /**

    * @param args

    */

   public static void main(String[] args) {

      String path ="E:/xp/test";

      File parent =new File(path);

      //printName(parent);

     

      File[] roots =File.listRoots();

      System.out.println(Arrays.toString(roots));

      for(File temp:roots){

        //printName(temp);

       

      }

   }

   /**

    * 輸出路徑

    */

   public static void printName(File src){

      if(null==src || !src.exists()){

        return ;

      }

      System.out.println(src.getAbsolutePath());

      if(src.isDirectory()){ //資料夾

        for(File sub:src.listFiles()){

           printName(sub);

        }

       

      }

   }

 

}

 

 

 

 

 

2. 原理與概念

一、概念

流:流動 、流向 從一端移動到另一端  源頭與目的地

程式 與  檔案|陣列|網路連線|資料庫  ,以程式為中心

二、IO流分類

1、流向: 輸入流與輸出流

2、資料:位元組流:二進位制,可以一切檔案 包括  純文字 doc 音訊、視訊等等

   字元流:文字檔案,只能處理純文字

3、功能:節點:包裹源頭

   處理:增強功能,提供效能

三、字元流與位元組流 (重點) 與檔案

1、位元組流

    輸入流:InputStream  read(byte[] b) 、read(byte[] b, int off, int len)  +close()

    FileInputStream()

    輸出流:OutputStream write(byte[] b)  write(byte[] b, int off, int len)  +flush() +close()

    FileOutputStream

2、字元流

   輸入流:Reader read(char[] cbuf) read(char[] cbuf, int off, int len)  +close()

   FileReader()

   輸出流:Writer  write(char[] cbuf) write(char[] cbuf, int off, int len) +flush() +close()

          write(String str, int off, int len)

   FileWriter()

四、操作

1、舉例:搬家         -->讀取檔案

   1)、關聯房子      --->建立與檔案聯絡

   2)、選擇搬家     --->選擇對應流

   3)、搬家    -->讀取|寫出

   a)、卡車大小   --->陣列大小

   b)、運輸 -->讀取、寫出

   4)、打發over     -->釋放資源

2、操作

1)建立聯絡

2)選擇流

3)操作  陣列大小+read 、write

4)釋放資源

注意:

   a:如果我們沒有明確說明按照什麼分,預設按照資料型別分。

   b:除非檔案用windows自帶的記事本開啟我們能夠讀懂,才採用字元流,否則建議使用位元組流。 

 

4. 字元流

字元流:只能處理 純文字,全部為可見字元  .txt  .html

節點流 Reader FileReader

          Writer FileWriter

一、純文字讀取

1、建立聯絡

2、選擇流 Reader FileReader

3、讀取 char[] flush =new char[1024];

4、關閉

二、純文字寫出

1、建立聯絡

2、選擇流   Writer FileWriter

3、讀取 write(字元陣列,0,長度)+flush

   write(字串)

   append(字元|字串)

4、關閉

 

5. 處理流

處理流:增強功能、提供效能,節點流之上

一、緩衝流

1)、位元組緩衝流

BufferedInputStream

BufferedOutputStream

2)、字元緩衝流

BufferedReader   readLine()

BufferedWriter    newLine()

二、轉換流: 位元組流 轉為字元流   處理亂碼(編碼集、解碼集)

1、編碼與解碼概念

 編碼:  字元   ---編碼字符集>二進位制

 解碼 : 二進位制   --解碼字符集->      字元

2、亂碼:

1)編碼與解碼的字符集不統一

2)位元組缺少,長度丟失

3、檔案亂碼

InputStreamReader(位元組輸入流,"解碼集")

OutputStreamWriter(字元輸出流,"編碼集")

 

 

6. 其他流

一、節點流

1、位元組陣列 位元組 節點流

    輸入流:ByteArrayInputStream      read(byte[] b, int off, int len)  + close()

    輸出流:ByteArrayOutputStream   write(byte[] b, int off, int len)  +toByteArray()新增方法   不要使用多型

二、處理流

1、基本型別+String  保留資料+型別

  輸入流:DataInputStream    readXxx

  輸出流:DataOutputStream  writeXxx

2、引用型別 (物件) 保留資料+型別

   反序列化 輸入流:ObjectInputStream  readObject()

   序列化  輸出流:ObjectOutputStream  writeObject()

  注意:

1)、先序列化後反序列化;反序列化順序必須與序列化一致

2)、不是所有的物件都可以序列化, java.io.Serializable

      不是所有的屬性都需要序列化,transient

3、列印流 PrintStream  println() print()

4、三個常量 : System.in /out/err   System.setIn() setOut() setErr()

  

IO流概述

1、IO流概述

(1)用來處理裝置(硬碟,控制檯,記憶體)間的資料。

(2)java中對資料的操作都是通過流的方式。

(3)java用於操作流的類都在io包中。

(4)按照流操作的資料的型別不同:分為位元組流和字元流。字元流是為了方便中文的操作而來的。   

(5)按照流的流向不同分為:輸入流,輸出流

2、概念

流:流動 、流向 從一端移動到另一端  源頭與目的地

程式 與  檔案|陣列|網路連線|資料庫  ,以程式為中心

3、IO流分類

a、流向: 輸入流與輸出流

b、資料:位元組流:二進位制,可以一切檔案 包括  純文字 doc 音訊、視訊等等

  字元流:文字檔案,只能處理純文字

c、功能:節點:包裹源頭

             處理:增強功能,提供效能

 

IO流常用基類

IO流常用基類:

(1)位元組流

輸出位元組流:OutputStream:位元組寫入流抽象類

        |--->FileOutputStream:

                        位元組寫入流

        |--->BufferedOutputStream:

                        位元組寫入流緩衝區

        |--->PrintStream:

                        列印流

輸入位元組流:InputStream:位元組讀取流抽象類

        |--->FileInputStream:

                        位元組讀取流

        |--->BufferedInputStream:

                        位元組讀取流緩衝區

(2)字元流      

輸出字元流:Writer:字元寫入流的抽象

        |--->FileWriter:

                        字元寫入流

        |--->BufferedWriter:

                        字元寫入流緩衝區

        |--->OutputStreamWriter:

                        字元通向位元組的轉換流(涉及鍵盤錄入時用)

        |--->OutputStreamWriter:      

                        列印流,可處理各種型別的資料

輸入字元流:Reader: 字元讀取流的抽象類

        |--->FileReader:

                        字元讀取流

                |--->LineNumberReader:

                        跟蹤行號的緩衝字元讀取流

        |--->BufferedReader:

                        字元讀取流緩衝區

        --->InputStreamReader:

                        位元組通向字元的轉換流(涉及鍵盤錄入時用)

(3)IO流常用基類方法摘要:

**位元組寫入流:OutputStream:

        void close() 關閉此輸出流並釋放與此流有關的所有系統資源。

        void flush()重新整理此輸出流並強制寫出所有緩衝的輸出位元組。

        abstract  void write(int b)  將指定的位元組寫入此輸出流。

        void write(byte[] b) 將 b.length 個位元組從指定的 byte 陣列寫入此輸出流。   

        void write(byte[] b, int off, int len)

                        將指定 byte 陣列中從偏移量 off 開始的 len 個位元組寫入此輸出流。

**位元組讀取流:InputStream:

        void close() 關閉此輸入流並釋放與該流關聯的所有系統資源。

        int available() (特有方法!!)

                返回此輸入流下一個方法呼叫可以不受阻塞地從此輸入流讀取(或跳過)的估計位元組數。

        abstract  int read() 從輸入流中讀取資料的下一個位元組。

        int read(byte[] b) 從輸入流中讀取一定數量的位元組,並將其儲存在緩衝區陣列 b 中。

        int read(byte[] b, int off, int len)  將輸入流中最多 len 個數據位元組讀入 byte 陣列。

        long skip(long n) 跳過和丟棄此輸入流中資料的 n 個位元組。

**字元寫入流:Writer:

        abstract  void close() 關閉此流,但要先重新整理它。

        abstract  void flush() 重新整理該流的緩衝。

        void write(int c) 寫入單個字元。

        void write(char[] cbuf) 寫入字元陣列。         

        abstract  void write(char[] cbuf, int off, int len) 寫入字元陣列的某一部分。

        void write(String str) 寫入字串。

        void write(String str, int off, int len) 寫入字串的某一部分。

**字元讀取流:Reader:

        abstract  void close() 關閉該流並釋放與之關聯的所有資源。

        int read() 讀取單個字元。

        int read(char[] cbuf)  將字元讀入陣列

        abstract  int read(char[] cbuf, int off, int len) 將字元讀入陣列的某一部分。

        long skip(long n)  跳過字元。

 

 

位元組流基類的子類

IO流常用位元組流基類的子類:

**寫入流:

(1)FileOutputStream:

        **構造方法:

        FileOutputStream(String name)

                建立一個向具有指定名稱的檔案中寫入資料的輸出檔案流。

        FileOutputStream(String name, boolean append)

                建立一個向具有指定 name 的檔案中寫入資料的輸出檔案流。

        FileOutputStream(File file)

                建立一個向指定 File 物件表示的檔案中寫入資料的檔案輸出流。

        FileOutputStream(File file, boolean append)

                建立一個向指定 File 物件表示的檔案中寫入資料的檔案輸出流。

        **方法摘要:

        public void flush()

        void close() 關閉此檔案輸出流並釋放與此流有關的所有系統資源。

        void write(int b) 將指定位元組寫入此檔案輸出流。

        void write(byte[] b, int off, int len)

                將指定 byte 陣列中從偏移量 off 開始的 len 個位元組寫入此檔案輸出流。

        void write(int b) 將指定位元組寫入此檔案輸出流。

(2)BufferedOutputStream:

        **構造方法:

        BufferedOutputStream(OutputStream out)

                建立一個新的緩衝輸出流,以將資料寫入指定的底層輸出流。

        BufferedOutputStream(OutputStream out, int size)

                建立一個新的緩衝輸出流,以將具有指定緩衝區大小的資料寫入指定的底層輸出流。

        **方法摘要:

        void flush() 重新整理此緩衝的輸出流。         

        void write(byte[] b, int off, int len)

                將指定 byte 陣列中從偏移量 off 開始的 len 個位元組寫入此緩衝的輸出流。

        void write(int b) 將指定的位元組寫入此緩衝的輸出流。