Java實現記事本

···
package com.shiyanlou.fileEditor;
import java.awt.;//abstract window tookit抽象窗口工具包
import java.awt.event.
; //此包定義了事件和事件偵聽器,以及事件偵聽器適配器,它是讓事件偵聽器的編寫過程更為輕松的便捷類。
import java.io.;//輸入輸出流
import javax.swing.
;//輕量級窗口組件
public class FileEditor extends JFrame {// 繼承標準窗口框架
// 定義一個私有的文件的絕對路徑文本域引用對象
private JTextField selectField;

// 定義一個私有的文件編輯區引用對象
private JTextArea editArea;

// 定義一個私有的保存按鈕引用對象
private JButton saveBtn;

// 定義一個私有的打開文件按鈕引用對象
private JButton openFileBtn;

// 定義一個私有的整型變量記錄目錄層次數,其初始值為0
private int level = 0;

public FileEditor() {
    this.init();
    // TODO Auto-generated constructor stub
}

public void init() {
    // 設置窗口標題, 父類的setTile
    this.setTitle("Editor");
    // 設置組件大小 窗口組件
    this.setBounds(300, 50, 600, 650);

    // 創建一個選擇框對象
    selectField = new JTextField(40);// 設置文本域大小

    // 創建一個選擇按鈕對象
    openFileBtn = new JButton("Browse");// 調用構造函數, 設置按鈕顯示文本
    // editArea = new JTextArea();

    // 為創建的按鈕對象添加監聽事件
    openFileBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // 若監聽到按鈕點擊事件, 則將層級記錄數重置為0
            // 獲取選擇文本域的string字符串
            FileEditor.this.level = 0;
            String path = selectField.getText();
            openDirOrFile(path.replaceAll("http://", "\\\\"));
        }
    });
    // 定義一個面板引用對象, 創建一個面板對象。
    // 以靜態常量為構造函數創建一個流布局對象
    // 以流布局對象作為面板對象的構造函數參數
    JPanel upPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));

    // 設置畫板的背景顏色
    upPanel.setBackground(Color.CYAN);

    // 將選擇框加入畫板中
    upPanel.add(selectField);

    // 將按鈕加入到畫板中
    upPanel.add(openFileBtn);

    //
    this.add(upPanel, BorderLayout.NORTH);

    /*
     * 創建文本編輯區,并加入到整個布局的中間區域
     */
    editArea = new JTextArea();

    ScrollPane scrollPane = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED);
    // 滾動面板添加文本編輯區組件
    scrollPane.add(editArea);

    this.add(scrollPane, BorderLayout.CENTER);

    /*
     * 創建保存按鈕,并為按鈕添加監聽事件
     */

    saveBtn = new JButton("Save");
    // 匿名內部類
    saveBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            saveFile();
        }
    });
    // 記事本下方
    JPanel southPanel = new JPanel();
    southPanel.setBackground(Color.green);
    southPanel.add(saveBtn);
    this.add(southPanel, BorderLayout.SOUTH);

    // 設置記事本默認關閉動作
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);
}

/*
 * 保存文件
 */
private void saveFile() {
    // TODO Auto-generated method stub
    // java類默認文件選擇窗口
    FileDialog fileDialog = new FileDialog(this, "Save File");
    // 設置需要保存文件的后綴
    fileDialog.setFile("unitiled.txt");
    // 設置為"保存"模式
    fileDialog.setMode(FileDialog.SAVE);
    // 設置窗口是否可見
    fileDialog.setVisible(true);
    // 獲取文件名
    String fileName = fileDialog.getFile();
    // 獲取文件當前目錄
    String dir = fileDialog.getDirectory();
    // 根據目錄名、文件名創建一個文件,即要保存的目錄文件
    // File.separator為文件默認分隔符
    File newFile = new File(dir + File.separator + fileName);
    PrintWriter pw = null;
    try {
        pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(newFile)));
        String str = editArea.getText();
        pw.print(str);
        pw.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        pw.close();
    }
}

private void openDirOrFile(String absolutePath) {
    // TODO Auto-generated method stub
    // absolutePath:制定目錄或文件的絕對路徑名

    File file = new File(absolutePath);
    // 判斷文件或者目錄是否存在
    if (!file.exists()) {
        editArea.setText("The file does not exist");
        // 判斷是否是一個目錄
    } else if (file.isDirectory()) {
        editArea.setText(null);
        showDir(file);
    } else if (file.isFile()) {
        try {
            // 文件輸入流對象
            FileInputStream fis = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String str = null;
            editArea.setText(null);
            while ((str = br.readLine()) != null) {
                editArea.append(str);
            }
            // 關閉字符流
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

private void showDir(File directory) {
    // TODO Auto-generated method stub

    // 獲得當前目錄
    File[] files = directory.listFiles();
    int len = files.length;

    for (int i = 0; i < len; ++i) {

        if (files[i].isDirectory()) {

            for (int j = 0; j < this.level; ++j) {
                editArea.append("    ");
            }
            editArea.append("|-- " + files[i].getName() + " (Folder)\r\n");
            
            this.level++;
            
            showDir(files[i]);
            
            this.level--;
        
        } else if (files[i].isFile()) {
            
            for (int j = 0; j < this.level; j++) {
                editArea.append("    ");
            }
        
            editArea.append("|-- " + files[i].getAbsolutePath() + "\r\n");
        }

    }
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    new FileEditor();
}

}
···

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1.import static是Java 5增加的功能,就是將Import類中的靜態方法,可以作為本類的靜態方法來...
    XLsn0w閱讀 1,267評論 0 2
  • 面向對象主要針對面向過程。 面向過程的基本單元是函數。 什么是對象:EVERYTHING IS OBJECT(萬物...
    sinpi閱讀 1,096評論 0 4
  • /** 記事本程序* 編寫時間:2010.3.12*/import java.awt.BorderLayout;i...
    霙愔閱讀 571評論 0 2
  • 小編費力收集:給你想要的面試集合 1.C++或Java中的異常處理機制的簡單原理和應用。 當JAVA程序違反了JA...
    八爺君閱讀 4,674評論 1 114
  • 作者 1 一個Java源程序是由若干個類 組成。 2 class 是Java的關鍵字,用來定義類。 3 Java應...
    java大濕兄閱讀 5,556評論 4 169