java分享第七天-02(讀取檔案)

來源:互聯網
上載者:User

標籤:nbsp   cat   err   info   接收   bcd   作用   span   輸出   

一 讀取檔案

public static void main(String[] args) throws FileNotFoundException,            IOException {        // 建立File對象        File srcFile = new File("");        // 選擇流        InputStream isInputStream = null;// 提升範圍        try {            isInputStream = new FileInputStream(srcFile);            // 操作不斷讀取緩衝數組            byte[] car = new byte[10];            int len = 0;// 接收實際讀取大小            // 迴圈讀取            while (-1 != isInputStream.read(car)) {                // 輸出位元組數組轉成字串                String info = new String(car, 0, len);                System.err.println(info);            }        } catch (FileNotFoundException e) {            e.printStackTrace();            System.out.println("檔案不存在");        } catch (IOException e) {            e.printStackTrace();            System.out.println("讀取檔案失敗");        } finally {            try {                if (null != isInputStream) {                    isInputStream.close();                }            } catch (Exception e) {                e.printStackTrace();                System.out.println("關閉檔案輸入資料流失敗");            }        }    }

 

二寫出檔案

public static void main(String[] args) throws FileNotFoundException,            IOException {        // 建立File對象目的地        File dest = new File("");        // 選擇流,檔案輸出資料流OutputStream   FileOutputStream        OutputStream out = null;// 提升範圍        try {            //true以追加的形式寫出檔案,否則是覆蓋            out = new FileOutputStream(dest,true);            String str="abcdedg";             //字串轉位元組數組            byte[] data=str.getBytes();            out.write(data,0,data.length);                            out.flush();//強制重新整理出去                    } catch (FileNotFoundException e) {            e.printStackTrace();            System.out.println("檔案未找到");        } catch (IOException e) {            e.printStackTrace();            System.out.println("寫出檔案失敗");        } finally {            try {                //釋放資源:關閉                if (null != out) {                    out.close();                }            } catch (Exception e) {                e.printStackTrace();                System.out.println("關閉檔案輸出資料流失敗");            }        }    }

 

java分享第七天-02(讀取檔案)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.