1. 程式人生 > >【Java】關於檔案

【Java】關於檔案

此程式實現了建立一個資料夾及其兩個子檔案,一個為data.txt,一個為filenew.txt,資料夾名字為create,程式包名為readW

import java.io.*;
public class createFile {
    public static void main(String[] arg) throws IOException{
        String s;
        File file = new File("create");
        if(!file.exists()){
            file.mkdir();
        }

        if
(file.isDirectory()){ File nfile = new File(file,"filenew.txt"); File ndata = new File(file,"data.txt"); if(!nfile.exists()){ try { nfile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } System.out
.println("檔案的絕對路徑為:"+nfile.getAbsoluteFile()); if(!ndata.exists()){ ndata.createNewFile(); } System.out.println("檔案的絕對路徑為:"+ndata.getAbsoluteFile()); PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(ndata))); int
a = 0; int b = 1; int temp; while(b < 1000){ temp = b; b = a+b; a = temp; pw.print(a+"\t"); } pw.close(); } try { BufferedReader br = new BufferedReader(new FileReader("C:\\Program Files\\Java\\新建資料夾\\Diary\\ReadW\\create\\filenew.txt")); System.out.println("檔案的內容為:"); try { while((s = br.readLine())!=null){ System.out.println(s); } } catch (IOException e) { e.printStackTrace(); } br.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }

程式讀取文字內容為:

這裡寫圖片描述

程式向文本里寫入斐波那契數列:

這裡寫圖片描述

這裡要注意幾個問題:
1.一開始找一個bug找了很久,這時候資料夾和檔案都已經新建了,當時我寫的輸出檔案絕對路徑的程式碼寫在了判斷檔案是否存在的if語句內,導致只有第一次能輸出路徑,所以保險的做法是把輸出路徑語句寫在外面。
2.出現錯誤filenotfound,說明要讀取的檔案沒有在工程所在的目錄下,因此保險的做法是將檔案的絕對路徑作為引數。

其實仔細分析程式可以發現,
新建一個資料夾、檔案分成固定的兩步套路:

File file = new File(“create”);//1.先new出來;
file.mkdir();//2.建立
File nfile = new File(file,”filenew.txt”);
nfile.createNewFile();

只是說涉及到異常的處理,要麼就要try catch,要麼就要throws丟擲異常;
其次,標準輸入輸出和位元組流字元流的轉換,就要用到匿名字元流等類。