簡體   English   中英

從JTextArea的輸出保存和打開文件

[英]Saving and opening files from output of JTextArea

我正在嘗試將JtextArea的輸出保存到文本文件。 然后,用戶可以單擊“打開”,它將打開文件目錄,但是我的保存文件不在那里?

有什么幫助嗎?

    import java.awt.BorderLayout;

公共類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();
}

}

您已經定義了saveFile(String fileName,String txtString)方法。 但是您沒有在程序中的任何地方調用saveFile方法。 因此,該文件將不會保存。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM