1. 程式人生 > 其它 >Java:檔案操作例項

Java:檔案操作例項

檔案操作

檔案寫入

import java.io.*;
public class Main {
    public static void main(String[] args){
        try{
            BufferedWriter file1 = new BufferedWriter(new FileWriter("a.txt"));
            file1.write("hello");
            file1.close();
            System.out.println("creation succeeded");
        } catch (IOException e){
        }
    }
}

檔案內容讀取

public class Main {
    public static void main(String[] args){
        try {
            BufferedReader reader = new BufferedReader(new FileReader("a.txt"));
            String str;
            while ((str = reader.readLine()) != null){
                System.out.println(str);
            }
        } catch (IOException e){
        }
    }
}

刪除檔案

public class Main{
    public static void main(String[] args){
            File file = new File("c:\\Users\\zzzzo\\test.txt");
            if (file.delete()) System.out.println(file.getName() + " is deleted");
            else System.out.println("Deleting failed");
    }
}

test.txt需要提前建立