天天看點

JAVA 檔案的建立與寫入

檔案的建立

首先,在指定的路徑下建立檔案,若存在則删除建立新檔案。

在類中得到工程的路徑:-System.getProperty(“user.dir”)

String path = System.getProperty("user.dir");
        System.out.println(path);
        String fileName = path+File.pathSeparator+"File"+
        File.pathSeparator+"1.txt";
        File file = new File(fileName);
        if(file.exists()){
            file.delete();
        }
            file.createNewFile();
           

下一步要做的就是向檔案中寫入内容。

基本的檔案輸出

FileWriter

FileWriter對象可以向文本檔案寫入資料。

在I/O類庫中常使用流這個概念,它代表任何有能力産出資料的源對象或者有能力接收資料源的接收端對象。在Java中,很少使用單一的類來建立流對象,而是通過疊合多個對象來提供所期望的功能,也可以稱作裝飾器模式。

/*開始寫入*/
        /*用來寫入檔案的便捷類*/
        FileWriter fr= new FileWriter(file);    
        /*将文本寫入輸出流,緩沖各個字元,進而提供字元、數組、字元串的高效寫入*/
        BufferedWriter bw = new BufferedWriter(fr); 
        /*向文本輸出流列印對象的格式化表示*/
        PrintWriter out = new PrintWriter(bw);      
        out.print("hello");
        out.close();
           

可以看到,裝飾器模式的缺點在于增加了代碼的複雜性。但它也提供了相當多的靈活性,讓我們可以混合和比對屬性。