1. 程式人生 > 其它 >IO流檔案和標準流

IO流檔案和標準流

1.File

  1. 建立FIle例項

    new File(String path);

  • 測試方法的使用:

    1. renameTo(File)把檔案重新命名到指定的檔案路徑下//原來的檔案會消失

      1.renameTo(File)把檔案重新命名到指定的檔案路徑下//原來的檔案會消失
      boolean b = file1.renameTo(file);
      
    2. //createNewFile()如果檔案存在返回false,如果這個檔案不存在則建立
      //delete(),刪除檔案

       File file3 = new File("hello.txt");
      if( file3.createNewFile()) System.out.println("建立成功");
      if( file3.delete()) System.out.println("刪除成功");
      
    3. mkdir():檔案目錄的建立

      delete():刪除目錄,要想刪除成功檔案下不能有東西

      // 檔案目錄的建立
       File file2 = new File("file");
       if (file2.mkdir()) System.out.println("目錄建立成功");
       if( file2.delete()) System.out.println("目錄刪除成功");/
      
    4. getParent():獲取當前檔案的上級目錄,可以用來在這個檔案的同級目錄下建立其他的檔案

2. 流的分類

3.流操作

  1. 文字檔案,使用字元流來處理
  2. 非文字檔案,使用位元組流來處理
  3. FileReader和FileInputStream都可以用陣列來讀取,一次讀取多個字元或位元組
讀取檔案內容
  • 讀取檔案的內容 1.獲取檔案 2. 建立處理流 3. 操作檔案 4.關閉流

  • 程式碼發現運用FileReader字元輸入流讀取檔案可以讀取出檔案中 的中文不會亂碼,單純的複製不會亂碼;FileReader讀取的是字元

    public class StreamTest {
        public static void main(String[] args) throws IOException {
            //  把檔案裡面的內容讀取到控制檯
            // 1. 例項化檔案File,指明需要操作的檔案
            File file = new File("test.txt");
            // 2. 提供一個具體的輸入輸出流對檔案進行操作
            FileInputStream fileInputStream = new FileInputStream(file);
            // 3. 讀取read();讀取到檔案末尾時會返回-1,每次讀取read後文件指標就會後移,且讀取出來的資料是int型別ascii碼值
            int e = fileInputStream.read();
            while (e != -1){
                System.out.print((char) e);
                e = fileInputStream.read();
            }
            // 4.關閉流操作
            fileInputStream.close();
        }
    }
    
  • FileReader一次讀取多個字元的操作

    //   FileReader一次讀取多個字元
    public void test1() {
        FileReader filereader = null;
        try {
            // 1. 指定需要操作的檔案並且定義操作流
            filereader = new FileReader(new File("test.txt"));
            // 2. 取資料
            char[] cufn = new char[5];
            int len = 0;
            while ((len = filereader.read(cufn)) != -1) {
                System.out.print(new String(cufn, 0, len));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //3. 關閉流資源
            try {
                filereader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
向檔案寫入內容
  • FileWriter注意事項

    1. 如果給出的檔案File不存在,則會自動建立檔案;

    2. FileWriter使用的構造器是new FileWriter(file)/new FileWriter(file,fales),在對檔案進行寫入操作的時候,就會對檔案原來的內容進行覆寫

    3. FileWriter使用的構造器是new FileWriter(file,true)就會在檔案原來的內容後面追加

      public void test1() throws IOException {
          //
          File file = new File("head.txt");
          FileWriter fileWriter = new FileWriter(file,true);
          fileWriter.write("I like java");
          fileWriter.write("I like java");
          fileWriter.close();
      }
      
  • 利用FileReader和FileWrite進行檔案的複製操作

        // 對一個檔案進行復制
        public void test2() throws IOException {
            FileReader fileReader = null;
            FileWriter fileWriter = null;
            try {
                fileReader = new FileReader("test.txt");
                fileWriter = new FileWriter("testCopy.txt",true);
                int i;
                while ((i=fileReader.read())!=-1){
                    fileWriter.write(i);
                }
    
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                System.out.println("複製完畢");
                fileReader.close();
                fileWriter.close();
            }
        }
    
3.複製圖片
  • 注意事項:

    1. 由於圖片的底層是一個位元組流的檔案,運用FileReader和FileWrite複製會出現問題,想要複製需要運用位元組流(FileInputStream)來處理

      // 嘗試複製一個圖片,位元組流的檔案
      public void test3() throws IOException {
          FileInputStream fileReader = null;
          FileOutputStream fileWriter = null;
          try {
              fileReader = new FileInputStream("test.png");
              fileWriter = new FileOutputStream("testCopy.png");
              int i;
              while ((i=fileReader.read())!=-1){
                  fileWriter.write(i);
              }
      
          } catch (FileNotFoundException e) {
              e.printStackTrace();
          } finally {
              System.out.println("複製完畢");
              fileReader.close();
              fileWriter.close();
          }
      }
      

4.緩衝流

緩衝流是對原有的四個節點流的包裝,提高他們的效率;工作中不會使用四種基本的節點流

緩衝流使用:Buffer+四種基本的節點流

內部提供了一個緩衝區:資料會讀到緩衝區,緩衝區滿了後一次性寫出去,緩衝區提高了效率(flush()重新整理緩衝區)

程式碼:利用位元組流: BufferInputStream和BufferOutputStream實現對圖片的複製:

 bufferedInputStream= new BufferedInputStream(fileInputStream);        bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
public void test1()  {    //    FileInputStream fileInputStream = null;    FileOutputStream fileOutputStream = null;    BufferedInputStream bufferedInputStream = null;    BufferedOutputStream bufferedOutputStream = null;    try {        // 建立輸入輸出流        fileInputStream= new FileInputStream("test.png");        fileOutputStream = new FileOutputStream("testCopy.png");        //  建立緩衝區,優化輸入輸出流        bufferedInputStream= new BufferedInputStream(fileInputStream);        bufferedOutputStream = new BufferedOutputStream(fileOutputStream);        // 讀取複製檔案      // 此處是位元組流的Buffer        byte[] copy =new byte[1024];        int len;        while ((len = bufferedInputStream.read(copy)) != -1){            bufferedOutputStream.write(copy,0,len);        }    } catch (FileNotFoundException e) {        e.printStackTrace();    } catch (IOException e) {        e.printStackTrace();    } finally {        try {            // 關閉資源,從外層開始關閉            bufferedInputStream.close();            bufferedOutputStream.close();            fileInputStream.close();            fileOutputStream.close();        } catch (IOException e) {            e.printStackTrace();        }    }}

5.轉換流

轉換流也屬於處理流對節點流進行包裝

  1. InputStreamReader
    • 在讀取的時候把讀取出來的位元組流資料轉化為字元流的資料載入程式中
  2. OutputStreamWrite
    • 程式在將字元流的資料轉化為位元組流的資料寫入檔案

程式碼:實現了對文字檔案的複製和顯示到控制檯

public void test() throws IOException {    InputStreamReader inputStreamReader = null;    OutputStreamWriter outputStreamWriter = null;    try {        inputStreamReader = new InputStreamReader(new FileInputStream("test.txt"),"UTF-8");        outputStreamWriter = new OutputStreamWriter(new FileOutputStream("testCopy.txt"),"UTF-8");        char[] copy = new char[1024];        int len;        while ((len = inputStreamReader.read(copy)) != -1) {            String s = new String(copy, 0, len);            System.out.print(s);            outputStreamWriter.write(s);        }    } catch (FileNotFoundException e) {        e.printStackTrace();    } finally {        inputStreamReader.close();        outputStreamWriter.close();    }}

6.標準的輸入輸出流

  1. System.in 標準的輸入流,預設從鍵盤輸入
  2. System.out 標準的輸出流,預設輸出到控制檯

鍵盤獲取一行字串

public static void main(String[] args) throws IOException {    BufferedReader bufferedReader = null;    try {        bufferedReader = new BufferedReader(new InputStreamReader(System.in));        System.out.println("請輸入一行字串");        while (true){            String data = bufferedReader.readLine();            if("e".equalsIgnoreCase(data)||"exid".equalsIgnoreCase(data))  //不考慮大小寫,比較是否一樣                break;            System.out.println(data);        }    } catch (IOException e) {        e.printStackTrace();    } finally {        bufferedReader.close();    }}