io編程

http://www.51gjie.com/java/77

  • 創(chuàng)建文件和目錄
在當(dāng)前工程工作路徑下創(chuàng)建文件和文件夾 

  // create file
        File file = new File("hello.txt");
        try {
            file.createNewFile();
        } catch (IOException e) {


        }

        // create dir
        File files = new File("files");
        files.mkdir();

        // 創(chuàng)建多級(jí)目錄
        File file1 = new File("parent/imgs");
        file1.mkdirs();

在指定目錄下創(chuàng)建文件, 
目錄必須要已經(jīng)存在的, 
否則將拋出 異常
java.io.IOException: No such file or directory


 // :
路徑分隔符
        System.out.println(File.pathSeparator);
        System.out.println(File.pathSeparatorChar);


        // / 
默認(rèn)名稱分隔符
        System.out.println(File.separator);
        System.out.println(File.separatorChar);


 // 獲取文件列表
        File file2 = new File("/Users/benjamin/IntelliJIdeaProjects/IO/");
        File[] listFiles = file2.listFiles();

  • 字節(jié)流讀取
單純的字節(jié)流讀取, 并把讀取的字節(jié)流存儲(chǔ)到一個(gè)字節(jié)數(shù)組中 

// 限制在1kb大小的數(shù)組內(nèi)
        // Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1024
        File file3 = new File("hello.txt");
        // bytes
        long length = file3.length();
        
        try {
            FileInputStream in = new FileInputStream(file3);
            byte[] b = new byte[1024];
            int len = 0;
            int temp = 0; //全部讀取的內(nèi)容都使用temp接收
            // 每次循環(huán)讀取1個(gè)字節(jié), 用temp臨時(shí)存儲(chǔ)讀取得到的1個(gè)字節(jié)
            while ((temp = in.read()) != -1) { //當(dāng)沒有讀取完時(shí),繼續(xù)讀取
                // 把讀取到的字節(jié)放到 字節(jié)數(shù)組b
                b[len] = (byte) temp;
                len++;
            }
            in.close();
            System.out.println(new String(b, 0, len));

        } catch (IOException e) {
            e.printStackTrace();
        }


FileInputStream 從內(nèi)存中讀出數(shù)據(jù)到byte[]中然后,使用FileOutputStream寫入文件中。

       FileInputStream fis = null;
         FileOutputStream fos = null;

        try {
            fis = new FileInputStream("hello.txt");

            fos = new FileOutputStream("b.txt");
            
            
            byte[] bytes = new byte[1024];

            while ((fis.read(bytes)) != -1) {
                fos.write(bytes);// 寫入數(shù)據(jù)
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 關(guān)閉流
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            
        }

  • 寫入字節(jié)流

flush()
OutputStream的flush()方法將所有寫入到OutputStream的數(shù)據(jù)沖刷到相應(yīng)的磁盤中。比如,如果輸出流是FileOutputStream,那么寫入到其中的數(shù)據(jù)可能并沒有真正寫入到磁盤中。即使所有數(shù)據(jù)都寫入到了FileOutputStream,這些數(shù)據(jù)還是有可能保留在內(nèi)存的緩沖區(qū)中。通過調(diào)用flush()方法,可以把緩沖區(qū)內(nèi)的數(shù)據(jù)刷新到磁盤(或者網(wǎng)絡(luò),以及其他任何形式的目標(biāo)媒介)中。

close()
當(dāng)你結(jié)束數(shù)據(jù)寫入時(shí),需要關(guān)閉OutputStream。通過調(diào)用close()可以達(dá)到這一點(diǎn)。因?yàn)镺utputStream的各種write()方法可能會(huì)拋出IO異常,所以你需要把調(diào)用close()的關(guān)閉操作方在finally塊中執(zhí)行。

  • 不管流是不是被自動(dòng)關(guān)閉, 我們都要在finally里手動(dòng)關(guān)閉下

http://www.javapractices.com/topic/TopicAction.do?Id=8

https://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html

單純的寫入字節(jié)流

  // 第1步、使用File類找到一個(gè)文件
        File file3 = new File("hello2.txt");    // 聲明File對(duì)象
        // 第2步、通過子類實(shí)例化父類對(duì)象
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file3);

            // 第3步、進(jìn)行寫操作
            String str = "Hello World!!!";        // 準(zhǔn)備一個(gè)字符串
            byte[] bytes = str.getBytes();            // 只能輸出byte數(shù)組,所以將字符串變?yōu)閎yte數(shù)組
            out.write(bytes);                        // 將內(nèi)容輸出,保存文件


        } catch (IOException e) {
            e.printStackTrace();
        }finally {

            // 把輸出字節(jié)流關(guān)了
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }



讀取并寫入字節(jié)字節(jié)流
 FileInputStream fis = null;
         FileOutputStream fos = null;

        try {
            fis = new FileInputStream("hello.txt");

            fos = new FileOutputStream("b.txt");
            
            
            byte[] bytes = new byte[1024];

            while ((fis.read(bytes)) != -1) {
                fos.write(bytes);// 寫入數(shù)據(jù)
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 關(guān)閉流
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            
        }

  • try-catch-finall

https://www.ibm.com/developerworks/cn/java/j-lo-finally/

只有與 finally 相對(duì)應(yīng)的 try 語句塊得到執(zhí)行的情況下,finally 語句塊才會(huì)執(zhí)行。

The finally Block

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return,continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

這句話是說, 不管是否出現(xiàn)異常, finally 語句一定會(huì)執(zhí)行的,
即便是 在 try語句中執(zhí)行了 方法的return 操作,
finally也還是會(huì)執(zhí)行的, 所以 finally可以執(zhí)行一些方法返回后的對(duì)代碼的清空操作, 比如關(guān)閉流的操作。

public class Test {
    public static void main(String[] args) {
        System.out.println("return value of test(): " + test());
    }

    public static int test() {
        int i = 1;

        try {
            System.out.println("try block");
            return i;
        } finally {
            System.out.println("finally block");
        }
    }
}

打印:

try block
finally block
return value of test(): 1


Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

這段話是說, 在 try和catch語句塊中執(zhí)行了虛擬機(jī)退出或者 線程終止也會(huì)導(dǎo)致finally語句不會(huì)執(zhí)行。

刪除文件和文件夾

  • 刪除文件
刪除一個(gè)單獨(dú)的文件

File file3 = new File("b.txt");
        if (file3.exists()) {
            file3.delete();
        }


    /**
     * Delete a file or a directory and its children.
     * @param file The directory to delete.
     * @throws IOException Exception when problem occurs during deleting the directory.
     */
    private static void delete(File file) throws IOException {

        for (File childFile : file.listFiles()) {

            if (childFile.isDirectory()) {
                delete(childFile);
            } else {
                if (!childFile.delete()) {
                    throw new IOException();
                }
            }
        }

        if (!file.delete()) {
            throw new IOException();
        }
    }

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • IO編程概念 IO在計(jì)算機(jī)中指Input/Output,也就是輸入和輸出。由于程序和運(yùn)行時(shí)數(shù)據(jù)是在內(nèi)存中駐留,由C...
    時(shí)間之友閱讀 784評(píng)論 0 0
  • IO在計(jì)算機(jī)中是指input/output,也就是輸入和輸出。由于程序和運(yùn)行時(shí)數(shù)據(jù)是在內(nèi)存中駐留,由CPU這個(gè)超快...
    Sun_atom閱讀 1,780評(píng)論 0 0
  • 阿超想要逃離這個(gè)城市,以前腦海里也蹦出過這個(gè)念頭,但這次突如其來的強(qiáng)烈感讓他惡心。這種感覺好比回流的馬桶。阿超從來...
    埃爾_e8f8閱讀 264評(píng)論 0 2
  • 今年九月,如愿,工作兩年后,回歸到大學(xué)校園,繼續(xù)我樂此不疲的青春。 參加工作兩年之后,心境相較于畢業(yè)之時(shí),確有很大...
    深藍(lán)雨閱讀 938評(píng)論 0 3
  • 云幕低垂曲徑長, 雪枝斜掛莽原荒。 誰曾感念移溫室? 瘦盡西風(fēng)碧四方!
    素雪妖嬈閱讀 290評(píng)論 0 0

友情鏈接更多精彩內(nèi)容