文件写入问题 - 文件为空

时间:2015-08-10 23:56:40

标签: java swing file file-io io

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.BadLocationException;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import java.awt.CardLayout;
import javax.swing.JSplitPane;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.awt.event.ActionEvent;
import javax.swing.JEditorPane;
import java.awt.Color;
import java.awt.Font;
import javax.swing.DropMode;
import javax.swing.JScrollBar;
import javax.swing.SwingConstants;

public class Program extends JFrame {

    private JPanel contentPane;
    private JTextField textField;
    private JTextField textField_1;

    /**
     * Launch the application.
     */

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Program frame = new Program();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    /**
     * Create the frame.
     *
     * @throws BadLocationException
     */
    public Program() throws BadLocationException {
        double points = 0;
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(0, 0, 1200, 760);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JEditorPane dtrpnTypeTextHere = new JEditorPane();
        dtrpnTypeTextHere.setContentType("type/normal");
        dtrpnTypeTextHere.setToolTipText("");
        dtrpnTypeTextHere.setFont(new Font("Arial", Font.PLAIN, 16));
        dtrpnTypeTextHere.setForeground(Color.GREEN);
        dtrpnTypeTextHere.setBackground(Color.BLACK);
        dtrpnTypeTextHere.setBounds(10, 23, 1152, 671);
        contentPane.add(dtrpnTypeTextHere);
        int length = dtrpnTypeTextHere.getDocument().getLength();
        String text = dtrpnTypeTextHere.getDocument().getText(0, length);
        JLabel lblNewLabel = new JLabel("Power Text Editor");
        lblNewLabel.setBackground(Color.BLACK);
        lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
        lblNewLabel.setForeground(Color.GREEN);
        lblNewLabel.setBounds(515, 0, 125, 14);
        contentPane.add(lblNewLabel);
        JLabel lblFileName = new JLabel("File Name:");
        lblFileName.setBounds(660, 703, 75, 14);
        contentPane.add(lblFileName);
        JButton btnFinishEditing = new JButton("Finish editing");
        btnFinishEditing.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                BufferedWriter writer = null;
                try {
                    //create a temporary file
                    File logFile = new File("yas.txt");

                    // This will output the full path where the file will be written to...
                    System.out.println(logFile.getCanonicalPath());
                    writer = new BufferedWriter(new FileWriter(logFile));
                    writer.write(text);
                } catch (Exception e1) {
                    e1.printStackTrace();
                } finally {
                    try {
                        // Close the writer regardless of what happens...
                        writer.close();
                    } catch (Exception e1) {
                    }

                    System.out.println("Quit because of user exit");
                    System.exit(0);

                }
            }
        });
        btnFinishEditing.setForeground(Color.GREEN);
        btnFinishEditing.setBackground(Color.BLACK);
        btnFinishEditing.setBounds(532, 699, 108, 23);
        contentPane.add(btnFinishEditing);

        textField_1 = new JTextField();
        textField_1.setBounds(726, 700, 131, 20);
        contentPane.add(textField_1);
        textField_1.setColumns(10);

    }
}

有代码,我在制作文件时遇到问题,当我输入内容时,它在文件中显示为空白。

2 个答案:

答案 0 :(得分:2)

您正在事件驱动环境中运行,这意味着在创建组件和显示UI以及发生的事情之间,时间已经过去。

这意味着当你做某事......

        JEditorPane dtrpnTypeTextHere = new JEditorPane();
        dtrpnTypeTextHere.setContentType("type/normal");
        dtrpnTypeTextHere.setToolTipText("");
        dtrpnTypeTextHere.setFont(new Font("Arial", Font.PLAIN, 16));
        dtrpnTypeTextHere.setForeground(Color.GREEN);
        dtrpnTypeTextHere.setBackground(Color.BLACK);
        dtrpnTypeTextHere.setBounds(10, 23, 1152, 671);
        contentPane.add(dtrpnTypeTextHere);
        int length = dtrpnTypeTextHere.getDocument().getLength();
        String text = dtrpnTypeTextHere.getDocument().getText(0, length);

然后就像......

btnFinishEditing.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        BufferedWriter writer = null;
        try {
            //create a temporary file
            File logFile = new File("yas.txt");

            // This will output the full path where the file will be written to...
            System.out.println(logFile.getCanonicalPath());
            writer = new BufferedWriter(new FileWriter(logFile));
            writer.write(text);
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            try {
                // Close the writer regardless of what happens...
                writer.close();
            } catch (Exception e1) {
            }

            System.out.println("Quit because of user exit");
            System.exit(0);

        }
    }
});

发生时,text的值不会改变,但JEditorPane的内容会有。您分配给text的值与JEditorPane的内容之间没有任何关系,除非您执行此操作的时刻。

所以,而不是这样做......

int length = dtrpnTypeTextHere.getDocument().getLength();
String text = dtrpnTypeTextHere.getDocument().getText(0, length);

在构造函数中,您应该在ActionListener ...

中执行此操作
btnFinishEditing.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        int length = dtrpnTypeTextHere.getDocument().getLength();
        String text = dtrpnTypeTextHere.getDocument().getText(0, length);
        BufferedWriter writer = null;
        try {
            //create a temporary file
            File logFile = new File("yas.txt");

            // This will output the full path where the file will be written to...
            System.out.println(logFile.getCanonicalPath());
            writer = new BufferedWriter(new FileWriter(logFile));
            writer.write(text);
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            try {
                // Close the writer regardless of what happens...
                writer.close();
            } catch (Exception e1) {
            }

            System.out.println("Quit because of user exit");
            System.exit(0);

        }
    }
});

作为一个例子。

您可能还想查看The try-with-resources Statement,这会降低文件编写try-catch-finally阻止的复杂性;)

作为旁注,避免使用null布局,像素完美布局是现代ui设计中的错觉。影响组件个体大小的因素太多,您无法控制。 Swing旨在与布局管理器一起工作,放弃这些将导致问题和问题的终结,您将花费越来越多的时间来纠正

答案 1 :(得分:0)

您的方法程序在程序开始时运行一次以设置UI。您在程序运行时声明并设置变量文本。鉴于在初始化程序时没有输入任何文本,您将始终在文件中获得一个空字符串。

您需要做的是将变量文本和读取文本的代码从JEditorPane dtrpnTypeTextHere移动到操作的开头。