读文本文件 FileChooser, FileFilter 的示例

读文本文件 FileChooser, FileFilter 的示例


import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.text.*;
/**
* This example illustrate how to
* a) read text file
* b) swing file chooser
* c) file filter
* @author hardneedl
*/
final public class TextReaderExapmle extends JFrame {
    private static final String FRAME_TITLE = "图形用户界面示例";
    private static final Dimension FRAME_SIZE = new Dimension(400, 350);
    private JButton fileChoosingButton;
    private JTextArea textArea;
    private JFileChooser fileChooser;

    public TextReaderExapmle() {
        super(FRAME_TITLE);
        init();
        doLay();
        attachListeners();
    }

    private void init() {
        fileChoosingButton = new JButton(new FileChooseAction());
        textArea = new JTextArea();

        fileChooser = new JFileChooser(System.getProperty("user.dir"));
        fileChooser.setFileFilter(new TextFileFilter());
        fileChooser.setMultiSelectionEnabled(false);
    }

    private void doLay() {
        Container container = getContentPane();
        container.add(fileChoosingButton, BorderLayout.NORTH);
        container.add(new JScrollPane(textArea), BorderLayout.CENTER);

        setSize(FRAME_SIZE);
        setVisible(true);
    }

    private void attachListeners () {
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(1);
            }
        });
    }
    /**
     * read text from the selected text file and convert text to string
     * @param reader
     * @return converted string
     */
    private static String readTextFromFile (final FileReader reader) {
        if (reader == null) return "";
        StringBuffer buf = new StringBuffer();

        final int CACHE_SIZE = 1024;
        final char[] cache = new char[CACHE_SIZE];
        try {
            int b;
            while ((b = reader.read(cache) ) != -1) {
                if (b < CACHE_SIZE)
                    buf.append(cache, 0, b);
                else
                    buf.append(cache);
            }
            reader.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
        return buf.toString();
    }

    /**
     * open file chooser action
     */
    private class FileChooseAction extends AbstractAction {
        static private final String ACTION_LABEL = "打开文件...";
        public FileChooseAction() {super(ACTION_LABEL);}
        public void actionPerformed(ActionEvent e) {

            int returnVal = fileChooser.showOpenDialog(fileChoosingButton);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                try {
                    FileReader reader = new FileReader (fileChooser.getSelectedFile() );
                    textArea.setText(readTextFromFile(reader));
                } catch(FileNotFoundException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /*file filter*/
    private class TextFileFilter extends FileFilter {
        private final java.util.List fileNameExtensionList = new ArrayList();
        public TextFileFilter() {
            fileNameExtensionList.add("txt");
            fileNameExtensionList.add("java");
            fileNameExtensionList.add("log");
            fileNameExtensionList.add("xml");
            fileNameExtensionList.add("htm");
            fileNameExtensionList.add("html");
            fileNameExtensionList.add("html");
            fileNameExtensionList.add("properties");
            fileNameExtensionList.add("svg");
        }
        public boolean accept(File f) {
            if (f.isDirectory()) return true;
            final String fileName = f.getName();
            int lastIndexOfDot = fileName.lastIndexOf('.');

            if (lastIndexOfDot == -1) return false;

            int fileNameLength = fileName.length();
            final String extension = fileName.substring(lastIndexOfDot+1, fileNameLength);

            return fileNameExtensionList.contains(extension);
        }
        public String getDescription() {
            StringBuffer buf = new StringBuffer("文本文件(");
            for (String fn : fileNameExtensionList)
                buf.append(MessageFormat.format("*.{0};", fn));
            return buf.append(')').toString();
        }
    }
    public static void main(String[] args) {new TextReaderExapmle();}
}

你可能感兴趣的:(Java)