java-IO流

來源:互聯網
上載者:User

標籤:操作   資料類型   讀取   str   鍵盤   sts   test   控制   結束   

1.使用File類操作檔案

2.FileReader,FileWriter,進行檔案的操作

   BufferedReader,BufferedWriter,進行檔案緩衝區操作

 DataInputStream,DataOutputStram,指定資料類型操作檔案

3.關閉流

// 執行個體化File對象
        File file = new File("E:\\tmp\\test.txt");
        // 當前檔案是否存在以及當前檔案是否是一個普通檔案
        if (file.exists() && file.isFile()) {
            System.out.println("該檔案已存在,覆蓋");
        } else {
            System.out.println("檔案不存在,建立檔案");
        }

        // 通過鍵盤輸入擷取寫入的資訊
        // 執行個體化一個BufferReader對象
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        // 執行個體化一個dataOutputStrem對象
        DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
        // 讀到的寫入資訊不為null
        while ((line = br.readLine()) != null) {
            if (line.toLowerCase().equals("end")) {
                break;
            }
            // 寫入資訊
            dos.writeBytes(line + "\r\n");
        }

        dos.close();
        br.close();

        // 讀取鍵盤輸入資訊
        BufferedReader br_read = new BufferedReader(new FileReader(file));
        String str=null;
        System.out.println("輸出檔案內容");
        while ((str = br_read.readLine()) != null) {
            System.out.println(str);
        }
        System.out.println("檔案讀取完畢");
        br_read.close();

 

重新導向標準IO流

System.in :inputStream類型,標準輸入資料流,預設的資料來源是鍵盤

System.out:PringStream類型,標準輸出資料流,預設控制台

System.err:PringStream類型,標準錯誤輸出資料流

以上三個在java.lang.System包中,他們出去整個java中開啟狀態

 

//重新導向輸出到檔案
        FileOutputStream fos = new FileOutputStream("E:\\tmp\\hello.txt");
        PrintStream ps = new PrintStream(fos);

        System.setOut(ps);
        System.out.println("這sdfsdfdsf中");
        System.out.println(new NormIo());

        fos.close();
        ps.close();


        // 重新導向標準輸入資料流
        /*FileInputStream fis = new FileInputStream("E:\\tmp\\hello.txt");
        System.setIn(fis);

        // 讀取內容
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        System.out.println("讀取標準輸入資料流");
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

        System.out.println("讀取結束");
        br.close();*/

 

java-IO流

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.