-2

Well, I brushed up on creating and writing to files in Java. However I can't figure out why my output won't write, my File file can't be found because it's being created/read in my main method, which, mind you, is in the same class.

public class EloManip {

    private JFrame frame;
    private JTextField textField;
    private JTextField textField_1;
    private JTextField textField_2;
    private JTextField textField_3;
    private JTextField textField_4;
    private JLabel lblFormat;
    private JTextField textField_5;
    private JLabel lblCase;
    private JLabel label;

    //Path p5 = Paths.get(System.getProperty("user.home"),"EloManip", "EloManipCases.log");

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        try {

            String content = "This is the content to write into file";

            File file = new File("/users/Peter/EloManipulation.txt");

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();

            System.out.println("Done");

        } catch (IOException e) {
            e.printStackTrace();
        }
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    EloManip window = new EloManip();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public EloManip() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);
        frame.setTitle("Elo Manipulation Case Creator by Cavasi");

        /*lblFormat = new JLabel("Format");
    lblFormat.setBounds(32, 180, 307, 14);
    frame.getContentPane().add(lblFormat);
         */

        textField = new JTextField();
        textField.setBackground(new Color(255, 255, 255));
        textField.setBounds(173, 34, 86, 20);
        frame.getContentPane().add(textField);
        textField.setColumns(10);

        JLabel lblEnterName = new JLabel("Enter name:");
        lblEnterName.setBounds(32, 37, 122, 14);
        frame.getContentPane().add(lblEnterName);

        JLabel lblEnterReason = new JLabel("Enter Reason:");
        lblEnterReason.setBounds(32, 62, 104, 14);
        frame.getContentPane().add(lblEnterReason);

        textField_1 = new JTextField();
        textField_1.setBackground(new Color(255, 255, 255));
        textField_1.setBounds(173, 59, 86, 20);
        frame.getContentPane().add(textField_1);
        textField_1.setColumns(10);

        JLabel lblEnterEvidence = new JLabel("Enter Evidence:");
        lblEnterEvidence.setBounds(32, 87, 131, 14);
        frame.getContentPane().add(lblEnterEvidence);

        textField_2 = new JTextField();
        textField_2.setBackground(new Color(255, 255, 255));
        textField_2.setBounds(173, 84, 86, 20);
        frame.getContentPane().add(textField_2);
        textField_2.setColumns(10);

        JLabel lblEnterDatemmddyy = new JLabel("Enter Date(MM/DD/YY):");
        lblEnterDatemmddyy.setBounds(32, 112, 136, 14);
        frame.getContentPane().add(lblEnterDatemmddyy);

        textField_3 = new JTextField();
        textField_3.setBackground(new Color(255, 255, 255));
        textField_3.setBounds(173, 109, 86, 20);
        frame.getContentPane().add(textField_3);
        textField_3.setColumns(10);

        JLabel lblEnterLength = new JLabel("Enter Length:");
        lblEnterLength.setBounds(32, 137, 122, 14);
        frame.getContentPane().add(lblEnterLength);

        textField_4 = new JTextField();
        textField_4.setBackground(new Color(255, 255, 255));
        textField_4.setBounds(173, 134, 86, 20);
        frame.getContentPane().add(textField_4);
        textField_4.setColumns(10);

        textField_5 = new JTextField();
        textField_5.setBackground(new Color(255, 255, 255));
        textField_5.setBounds(10, 207, 414, 20);
        frame.getContentPane().add(textField_5);
        textField_5.setColumns(10);

        JButton btnNewButton = new JButton("Generate Elo Manipulation Case");
        btnNewButton.setFont(new Font("Nirmala UI Semilight", Font.BOLD, 11));
        btnNewButton.setForeground(Color.BLACK);
        btnNewButton.setBackground(Color.GREEN);
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                //lblFormat.setText(textField)
                //JOptionPane.showMessageDialog(null, textField.getText() + " - " + textField_1.getText() + " - " + textField_2.getText() + " " + textField_3.getText() + " [" + textField_4.getText() + "]");
                textField_5.setText(textField.getText() + " - " + textField_1.getText() + " - " + textField_2.getText() + " " + textField_3.getText() + " [" + textField_4.getText() + "]");
                JOptionPane.showMessageDialog(null, "Successfully created Elo Manipulation Case!");
                Writer output;
                output = new BufferedWriter(new FileWriter(file, true));  
                output.append("New Line!");
                output.close();
            }
        });
        btnNewButton.setBounds(0, 238, 434, 23);
        frame.getContentPane().add(btnNewButton);

        lblCase = new JLabel("Case:");
        lblCase.setBounds(10, 182, 352, 14);
        frame.getContentPane().add(lblCase);

        label = new JLabel("");
        label.setBounds(269, 11, 155, 163);
        frame.getContentPane().add(label);

        Image img = new ImageIcon(this.getClass().getResource("/badlionsmall.png")).getImage();

        label.setIcon(new ImageIcon(img));
    }
}

File can't be resolved to a variable because it's being created/checked in my main method, but my action that needs to be written to the .txt file is not in the main method, but rather the initialize method. What do I do?

Tom
  • 16,842
  • 17
  • 45
  • 54
Cavasi
  • 1
  • 2
  • Local variables aren't scoped to the class of the method they appear in, they are scoped to the braces (`{}`) they appear in. If you want to be able to use a variable anywhere in your class, you need to make it a class variable. – azurefrog Dec 14 '15 at 21:40
  • 4
    If you have a new question, ask a new question. Don't overwrite this one. – Jeffrey Bosboom Dec 14 '15 at 21:59
  • As written many times, a new question belongs into a new post, not appended into this one. You can create a new question be clicking on "Ask Question" in the top right corner. – Tom Dec 14 '15 at 22:50

3 Answers3

1

Why isn't my file being appended?

Correct me if I am wrong ... but I think that this question is really about a compilation error. The problem is that the local variable file in the main method is not in scope in your listener.

The solution is to move the declaration of file. The simplest way would be to make it a static (private, final) field of EloManip.

(Putting state into statics is not generally a good idea, but if the state is effectively a constant, AND it is localized to a single class and its inner classes, there is not much harm. However, there is a more OO way of handling this ...)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • I fixed it, however now I have my text that's being written to it overwritten once I clck my button, check my thread now – Cavasi Dec 14 '15 at 21:50
  • 2
    You have "vandalized" your question by removing the problem that my Answer refers to. If you want me to answer your followup, put the original code back and ask your followup as an EDIT, or as a new Question. Start by reverting your last edit ... – Stephen C Dec 14 '15 at 21:55
  • 2
    @Cavasi please do not change your question. It invalidates answer(s). – Emz Dec 14 '15 at 21:57
0

You're actually declaring two FileWriter variables

  FileWriter fw = new FileWriter(file.getAbsoluteFile());
  BufferedWriter bw = new BufferedWriter(fw);
  Writer output;
  output = new BufferedWriter(new FileWriter(file, true));  

Have you tried using only one? I suspect the first one is clearing your contents, not the second one.

KarlM
  • 1,614
  • 18
  • 28
0

This worked for me;

public static void main(String[] args) throws IOException {
    File f = new File("test.txt");
    try(FileWriter fw = new FileWriter(f, true)) {
        fw.append("charsequence\r\n");
    } catch(IOException e) {
        e.printStackTrace();
    }
}

Remember that changes to the file will only show if you close it and then open it again.

Adam Martinu
  • 253
  • 1
  • 11
  • *"Remember that changes to the file will only show if you close it and then open it again."* - Not correct. A `flush()` will also work, and you don't have to open the file again (in this application) for the changes to show up in another application. – Stephen C Dec 14 '15 at 22:06
  • If he opens the file in a program such as notepad _before_ he flushes the stream, then no, the changes won't be visible. – Adam Martinu Dec 14 '15 at 22:09
  • That is correct. If he opens it in another program before he flushes OR closes. But he doesn't need to open it >>again<< in this application or another for the changes to be visible. A flush or close is sufficient. (Not for Notepad ... but for other applications which don't read the entire file at startup.) – Stephen C Dec 15 '15 at 02:59
  • Oh ok. I just assumed OP used notepad since my example (which is a shrinked version of OPs source) actually works, yet the changes weren't visible to him :) – Adam Martinu Dec 15 '15 at 03:45