从JTextArea的输出中保存和打开文件

时间:2014-02-04 15:44:07

标签: java file save jtextarea

我正在尝试将JtextArea的输出保存到文本文件中。然后用户可以单击打开它将显示文件目录,但我保存的文件不在那里?

任何帮助?

    import java.awt.BorderLayout;

public class hello扩展了JFrame {

static String summary;
private JPanel contentPane;
private JTextField textField;
private Queue<String> tillQueue;
private JTextArea textArea;
private int rndNumber;
private int currentLength;
private ArrayList<Integer> lengthList;
private Random r;
String output = "";
private JMenuBar mb;
private JMenu fileMenu;
private JMenuItem newItem, openItem, saveItem, exitItem;
private JFileChooser jc = new JFileChooser();

/**
 * Create the frame.
 */
public hello() {
    super ("Till Simulation");
    tillQueue = new LinkedList<String>();
    currentLength = 0;
    lengthList = new ArrayList<Integer>();
    r = new Random();

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 465, 370);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);
    contentPane.setBackground(Color.GRAY);

    textField = new JTextField();
    textField.setBounds(178, 275, 181, 27);
    contentPane.add(textField);
    textField.setColumns(10);

    final JButton btn1 = new JButton("RUN");
    btn1.setFont(new Font("Comic Sans MS", Font.PLAIN, 17));
    btn1.setBounds(369, 275, 70, 31);
    contentPane.add(btn1);

    JLabel lblNewLabel = new JLabel("Enter time in Minutes");
    lblNewLabel.setFont(new Font("Comic Sans MS", Font.PLAIN, 14));
    lblNewLabel.setBounds(10, 276, 158, 21);
    contentPane.add(lblNewLabel);

    textArea = new JTextArea();
    textArea.setBounds(0, 0, 449, 269);
    textArea.setBackground(Color.lightGray);
    contentPane.add(textArea);

    btn1.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int int1 = Integer.parseInt(textField.getText());
            if (e.getSource() == btn1) {
                simulation(int1);
                textArea.setText(output + "\n" + statistics());

            }
        }
    });

    //create menu
    mb = new JMenuBar();
    this.setJMenuBar(mb);

    JMenu fileMenu = new JMenu("File");

    newItem = new JMenuItem("New");
    newItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            tillQueue.clear();
            lengthList.clear();
            textArea.setText("");
            output = "";
        }
    });

    openItem = new JMenuItem("Open");
    openItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            //textArea.setText(OpenFile("simulation.txt"));
            if (e.getSource()== openItem){
                JFileChooser choose = new JFileChooser("C:/Users/Desktop");
                int x = choose.showOpenDialog(null);

                if (x == JFileChooser.APPROVE_OPTION)
                {
                    File file = choose.getSelectedFile();

                    try{
                        Desktop.getDesktop().open(file);
                    } catch(IOException e2){
                        System.out.println("you failed to open a file ");
                    }
                }
            }


        }
    });

    saveItem = new JMenuItem("Save");
    saveItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            //String saveFile = output + "\n" + statistics();
            if (e.getSource() == saveItem){
                summary = (output + "\n" + statistics());
                String Data = hello.summary;
                try{
                    BufferedWriter reader = new BufferedWriter(new FileWriter(new File("C:/Users/Desktop/Documents/addInfo.txt"), true));
                    reader.write(Data);
                    reader.newLine();
                    reader.close();

                    System.out.println("DONE");
                }catch(IOException e1){
                    System.out.println("Error is "+ e1);
                }
            }

        }
    });

    exitItem = new JMenuItem("Exit");
    exitItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            System.exit(0);
        }
    });

    mb.add(fileMenu);
    fileMenu.add(newItem);
    fileMenu.add(saveItem);
    fileMenu.add(openItem);
    fileMenu.add(exitItem);                 

}

public void simulation(int time)
{   
    output = "Time" + "\t" + "Random Num" + "\t" + "Queue Status" + "\n";
    for (int t = 1; t< time; t++)
    {
        rndNumber = r.nextInt(6);

        if (rndNumber == 2 || rndNumber == 4)
        {
            //t is added to queue

            tillQueue.add(String.valueOf(t));
            currentLength++;
        }

        else if ((rndNumber == 1 || rndNumber == 3) && !tillQueue.isEmpty())
        {
            tillQueue.remove();
            currentLength--;
        }

        if (tillQueue.isEmpty())
        {
            output += "\n" + t + rndNumber + "\t" + "Empty Queue";
        }

        else 
        {
            output += "\n" +  t + "\t" + rndNumber + "\t" + tillQueue.toString();
        }

        lengthList.add(new Integer(currentLength));
    }
}

public double calcMean()
{
    double mean = 0.0;
    int sumLength = 0;

    for (int i =0; i<lengthList.size(); i++)
    {
        sumLength = sumLength +(Integer)lengthList.get(i).intValue();
    }

    mean = (double)sumLength/lengthList.size();

    return mean;
}

public int MinimumQSize()
{

    //return lengthList.indexOf(Collections.min(lengthList.size()));
    int minimum = 0;
    for (int i = 1; i < lengthList.size(); i++)
    {
        if (lengthList.get(i) < minimum)
        {
            minimum = lengthList.get(i);
        }
    }
    return minimum;
}

public int MaxQSize()
{
    int max = 0;
    for (int z = 0; z< lengthList.size(); z++)
    {
        if (lengthList.get(z) > max)
        {
            max = lengthList.get(z);
        }
    }
        return max;
}
public double Variance()
{
    //int sumLength= 0;
    double temp = 0;
    for (int i = 0; i <lengthList.size(); i++)
    {
        //sumLength = sumLength +(Integer)lengthList.get(i).intValue();
        temp = calcMean() - lengthList.get(i).intValue();
        temp = Math.pow(temp,  2);
    }
    return temp;

}

public String statistics() {
    String stats = "";

    int m = MaxQSize();
    stats += "Max length: " +  m + "\n";

    int a = MinimumQSize();
    stats += "minimum size of queue " + a + "\n";

    double mean = calcMean();
    stats += "Mean of queue: " + mean + "\n";

    double v = Variance();
    stats += "Variance: " + v + "\n";
    return stats;
}

public static void saveFile(String fileName, String txtString){
    BufferedWriter b = null;
    try{
        b = new BufferedWriter(new FileWriter(fileName));
        try
        {
            b.write(txtString);
        }

        finally {
            b.close();

        }
    }
        catch (IOException e) {
            System.out.println("Save exception has occured");
        //  e.printStackTrace();
        }
    }

public static String OpenFile(String fileName)
{
    BufferedReader b = null;
    StringBuilder sb = new StringBuilder();
    try {
        b = new BufferedReader(new FileReader(fileName));
        try {
            String s;
                while((s = b.readLine()) != null){
                    sb.append(s + "\n");
                }
        } finally {
            b.close();
        }
    } catch (Exception ex){
        System.out.println("Read exception has occured");
    }

    return sb.toString();
}

}

1 个答案:

答案 0 :(得分:0)

您已定义saveFile(String fileName,String txtString)方法。但是你没有在程序中的任何地方调用saveFile方法。所以文件不会被保存。