简体   繁体   中英

How can I make my program create a new output file name everytime it is reopened?

I have a program which currently opens a GUI and allows the user to input their name as well as the languages which they know. When the Submit button is pressed this is then translated into a console output as well as a notepad file when ran as an executable JAR file. My problem is, everytime I close the program and reopen it then the previous saved outputs are deleted. How would I bypass this?

Runnable code:

package guiChallenge;

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

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import javax.swing.JCheckBox;
import javax.swing.UIManager;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.awt.event.ActionEvent;

public class guiChallenge extends JFrame {

    /**
     * 
     */
    private JPanel contentPane;
    private JTextField firstNameTextField;
    private JTextField lastNameTextField;
    private JCheckBox javaCheckBox, cCheckBox, c2CheckBox, pythonCheckBox, phpCheckBox, htmlCheckBox;
    String javaLanguage, cLanguage, c2Language, phpLanguage, pythonLanguage, htmlLanguage;

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

    /**
     * Create the frame.
     * @throws FileNotFoundException 
     */
    public guiChallenge() throws FileNotFoundException {

        PrintStream output = new PrintStream(new FileOutputStream("Report.txt"));
        System.setOut(output);

        setTitle("Programmer Entry");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JPanel namePanel = new JPanel();
        namePanel.setBorder(new TitledBorder(null, "Name", TitledBorder.LEADING, TitledBorder.TOP, null, null));
        namePanel.setBounds(10, 11, 414, 106);
        contentPane.add(namePanel);
        namePanel.setLayout(null);

        JLabel firstNameLabel = new JLabel("First Name: ");
        firstNameLabel.setBounds(10, 18, 81, 33);
        namePanel.add(firstNameLabel);

        JLabel lastNameLabel = new JLabel("Last Name: ");
        lastNameLabel.setBounds(10, 62, 89, 33);
        namePanel.add(lastNameLabel);

        firstNameTextField = new JTextField();
        firstNameTextField.setBounds(79, 24, 155, 20);
        namePanel.add(firstNameTextField);
        firstNameTextField.setColumns(10);

        lastNameTextField = new JTextField();
        lastNameTextField.setColumns(10);
        lastNameTextField.setBounds(79, 68, 155, 20);
        namePanel.add(lastNameTextField);

        JPanel languagesPanel = new JPanel();
        languagesPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Languages", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
        languagesPanel.setBounds(10, 128, 414, 122);
        contentPane.add(languagesPanel);
        languagesPanel.setLayout(null);

        javaCheckBox = new JCheckBox("Java");

        javaCheckBox.setBounds(6, 20, 97, 23);
        languagesPanel.add(javaCheckBox);

        cCheckBox = new JCheckBox("C");

        cCheckBox.setBounds(6, 46, 97, 23);
        languagesPanel.add(cCheckBox);

        c2CheckBox = new JCheckBox("C++");

        c2CheckBox.setBounds(6, 72, 97, 23);
        languagesPanel.add(c2CheckBox);

        phpCheckBox = new JCheckBox("PHP");

        phpCheckBox.setBounds(117, 20, 97, 23);
        languagesPanel.add(phpCheckBox);

        pythonCheckBox = new JCheckBox("Python");

        pythonCheckBox.setBounds(117, 46, 97, 23);
        languagesPanel.add(pythonCheckBox);

        htmlCheckBox = new JCheckBox("HTML");

        htmlCheckBox.setBounds(117, 72, 97, 23);
        languagesPanel.add(htmlCheckBox);

        JButton submitUserButton = new JButton("Submit User");
        submitUserButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {


                System.out.println("Applicant Report:");
                System.out.println();
                System.out.println("First Name: " + firstNameTextField.getText() + "    Last Name: " + lastNameTextField.getText());
                System.out.println();
                System.out.println("Languages known: ");

                if(javaCheckBox.isSelected() == true){
                System.out.println("Java");
                }

                if(cCheckBox.isSelected() == true){
                System.out.println("C");
                }

                if(c2CheckBox.isSelected() == true){
                System.out.println("C++");
                }

                if(phpCheckBox.isSelected() == true){
                System.out.println("PHP");
                }

                if(pythonCheckBox.isSelected() == true){
                System.out.println("Python");
                }

                if(htmlCheckBox.isSelected() == true){
                System.out.println("HTML");
                }

                System.out.println("");
                System.out.println("Languages not known: ");

                if(javaCheckBox.isSelected() == false){
                    System.out.println("Java");
                    }

                if(cCheckBox.isSelected() == false){
                    System.out.println("C");
                    }

                if(c2CheckBox.isSelected() == false){
                    System.out.println("C++");
                    }

                if(phpCheckBox.isSelected() == false){
                    System.out.println("PHP");
                    }

                if(pythonCheckBox.isSelected() == false){
                    System.out.println("Python");
                    }

                if(htmlCheckBox.isSelected() == false){
                    System.out.println("HTML");
                    }

                resetPanels();

            }
        });
        submitUserButton.setBounds(220, 46, 184, 23);
        languagesPanel.add(submitUserButton);
    }

    public void resetPanels(){
        firstNameTextField.setText("");
        lastNameTextField.setText("");
        javaCheckBox.setSelected(false);
        cCheckBox.setSelected(false);
        c2CheckBox.setSelected(false);
        phpCheckBox.setSelected(false);
        pythonCheckBox.setSelected(false);
        htmlCheckBox.setSelected(false);

    }
}

Thank you for your time.

So, the trouble here is that you're always writing to "report.txt". Every time you runthe code, you're overwriting it. Sadly, it's kinda messy to deal with that, since there's no easy way (that I know of) to store what you've written to across sessions, but there are a few ways to do it. Here's 2:

1) create the name a runtime. You can do something like:

String name = "report";
int count = 1;
if(new File(name + ".txt").exists()) {
    while(new File(name + count + ".txt").exists()) {
        count++;
    }
    name += "" + count;
}
name += ".txt";

i'm not sure the "" is necessary before + count , but I put it just in case you need to cast count to a String .

2) check all the files that already exist. You're always writing to the same folder, so you can just take advantage of the listFiles() method for files. It'll print out all the files within the file it's called on, so you can see what you've written to. I think it can only be called on directories though, so you'll have to work out what folder you're in first.

I'd say the first way is easier though. If you really want, you could also store what names you've used, or the index of which report or some other identifier in a .txt, .cfg, .ini, or whatever type of file, and just read it when the program starts up, then edit it when a report is made.

You could set your output to append instead of override, see this question: File Write - PrintStream append

 PrintStream output = new PrintStream(new FileOutputStream("Report.txt", true));

I took your code, switched your line with the line above (line ~55), and my file started looking like this:

Applicant Report:

First Name: Person    Last Name: TheirLName

Languages known: 
Java

Languages not known: 
C
C++
PHP
Python
HTML
Applicant Report:

First Name: AnotherGuy    Last Name: Doe

Languages known: 
PHP
Python

Languages not known: 
Java
C
C++
HTML

So, you may want to tweak how you do new lines and such in your output, but other than that it looks okay.

You could create a different file name every time by appending the user's name to a file called say "report_" + their name.

EDIT: I read through your code some more. Here's a fun thing that's maybe the better way to handle your output.

You can reduce the amount of times you call System.out but just appending everything you want to output to a running String (with newline characters ofc) and then just calling System.out on that. Then you can also just call output.write([String here]) once to get your desired results

FileOutputStream has the ability to append instead of erasing the original. Just use a different constructor like this:

    PrintStream output = new PrintStream(new FileOutputStream("Report.txt", true));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM