1. 程式人生 > >(作業系統實驗)簡單模擬檔案系統的基本操作

(作業系統實驗)簡單模擬檔案系統的基本操作

程式碼

//思路:使用者登入檔案系統,然後建立、開啟、讀、寫、關閉、刪除檔案

import java.io.*;
import java.util.*;

public class Main{

	public static void main(String[] args){
		Scanner scan = new Scanner(System.in);
		login();
		menu();
		String[] splits = new String[2];
		while(true){
			splits[0] = scan.next();
			splits[1] =scan.
next(); switch(splits[0]){ case "create": create(splits[1]); break; case "open": open(splits[1]); break; case "read": open(splits[1]); break; case "delete": delete(splits[1]); break; case "write": write(splits[1]); break
; case "close": close(splits[1]); break; } } } //登入 public static void login(){ Scanner scan = new Scanner(System.in); System.out.print("請輸入使用者名稱: "); String name = scan.next(); System.out.print("請輸入密碼:"); String password = scan.next(); System.out.println("恭喜,您已經登入檔案系統!"
); } //選單 public static void menu(){ System.out.println("--------------------------------------------------"); System.out.println("create 檔名---------------------------建立檔案"); System.out.println("delete 檔名---------------------------刪除檔案"); System.out.println("open 檔名----------------------------開啟檔案"); System.out.println("write 檔名----------------------------寫檔案"); System.out.println("read 檔名-----------------------------讀檔案"); System.out.println("close 檔名----------------------------關閉檔案"); } //建立檔案 public static void create(String filename){ try{ File dir = new File(".",filename); dir.createNewFile(); System.out.println(filename+"已經建立成功!"); }catch(Exception e){ e.printStackTrace(); } } //刪除檔案 public static void delete(String filename){ try{ File file = new File(filename); file.delete(); }catch(Exception e){ e.printStackTrace(); } } //讀檔案 public static void open(String filename){ try{ File file = new File(filename); BufferedReader br = new BufferedReader(new FileReader(file)); String str = null; while((str = br.readLine()) != null){ System.out.println(str); } br.close(); }catch(Exception e){ e.printStackTrace(); } } //寫檔案 public static void write(String filename){ try{ Scanner scan = new Scanner(System.in); File file = new File(filename); FileWriter fw = new FileWriter(file); String str = scan.next(); while(!str.equals("#")){ fw.write(str); str = scan.next(); } fw.close(); System.out.println("寫入完畢"); }catch(Exception e){ e.printStackTrace(); } } //關閉檔案 public static void close(String filename){ System.out.println(filename+"已經關閉!"); } }

結果

在這裡插入圖片描述