如何阅读文件内容?

时间:2013-12-01 18:59:39

标签: java file file-io

我有一个文本编辑器,我将用它来编辑HTML。我希望能够创建某种文件开启工具,然后将文本“打印”到文本区域。我不确定如何继续这样做。这是我的代码:

package main;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream.GetField;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class TextEditor {
static boolean saved = false;
static final JTextArea textArea = new JTextArea(20,50);
static final JFileChooser chooser = new JFileChooser("save");
static final JFileChooser openChooser = new JFileChooser("Open");
public static void start(){
    JFrame f = new JFrame("Text editor");
    JPanel savePanel = new JPanel();
    JButton sb = new JButton("Save");
    JButton qsb = new JButton("Quick save");
    JButton ob = new JButton("Open");

    sb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            save();
        }
    });

    qsb.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            quickSave();
        }
    });

    ob.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            open();
        }
    });

    savePanel.add(sb);
    savePanel.add(qsb);

    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    f.setLayout(new BorderLayout(2,1));
    f.add(savePanel,BorderLayout.PAGE_START);
    f.add(textArea);
    f.pack();
    f.setVisible(true);
}

public static void save(){
    File dir;
    chooser.showDialog(null, "Save");
    dir = chooser.getSelectedFile();
    System.out.println(dir);
    try {
        FileWriter fw = new FileWriter(dir);
        String text = textArea.getText().replace("\n", System.getProperty("line.separator").toString());
        fw.write(text);
        fw.close();
        saved = true;
    } catch (IOException e) {
        JOptionPane.showMessageDialog(null, e);
}
}

public static void quickSave(){
if (saved == false){
    JOptionPane.showMessageDialog(null, "You must save at least once to use this function");
}
else{
    File dir = chooser.getSelectedFile();
    String text = textArea.getText().replace("\n", System.getProperty("line.separator").toString());
    try{
    FileWriter fw = new FileWriter(dir);
    fw.write(text);
    fw.close();
    }catch(IOException e){
        JOptionPane.showMessageDialog(null, e);
        }
    }
}

public static void open(){
openChooser.showDialog(null, "Oopen");
File dir = openChooser.getSelectedFile();
//want to open file which is dir.
}
}

1 个答案:

答案 0 :(得分:1)

美好而轻松:

textArea.read(new FileReader(dir), null);

这就是它的全部内容。