Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: Problem trying to add a new file each time, without overwriting the previous.

  1. #1
    Junior Member
    Join Date
    Feb 2014
    Posts
    5
    My Mood
    Fine
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Problem trying to add a new file each time, without overwriting the previous.

    Hi, I was wondering if you can help, I am creating a questionaire that when the submit button is pressed, the information is saved into a .txt file and saved on the computer locally...for now. The end goal would be to have the information sent as an email.

    private void submitButtonActionPerformed(java.awt.event.ActionE vent evt)
    {
    int age;
    String q1,q2,q3,q4,q5,q6,q7,q8,q9,q10;
    age = Integer.parseInt(answer1.getText());
    q1 = answer1.getText();
    q2 = answer2.getText();
    q3 = answer3.getText();
    q4 = answer4.getText();
    q5 = answer5.getText();
    q6 = answer6.getText();
    q7 = answer7.getText();
    q8 = answer8.getText();
    q9 = answer9.getText();
    q10 = answer10.getText();

    Path newFile = Paths.get("C:/Users/David/Desktop/programming/questionaire/Files/questionaire.txt");
    if(Files.exists(newFile))
    {
    //trying to add code here to add an number on the end. i.e. questionaire1.txt
    }

    try
    {
    Files.deleteIfExists(newFile);
    newFile = Files.createFile(newFile);
    }
    catch (IOException e)
    {
    System.out.println("Error Creating File!");
    }
    System.out.println(Files.exists(newFile));

    try(BufferedWriter writer = Files.newBufferedWriter(newFile,Charset.defaultCha rset()))
    {
    writer.append(q1);
    writer.newLine();
    writer.append(q2);
    writer.newLine();
    writer.append(q3);
    writer.newLine();
    writer.append(q4);
    writer.newLine();
    writer.append(q5);
    writer.newLine();
    writer.append(q6);
    writer.newLine();
    writer.append(q7);
    writer.newLine();
    writer.append(q8);
    writer.newLine();
    writer.append(q9);
    writer.newLine();
    writer.append(q10);
    writer.newLine();
    writer.flush();
    }
    catch(IOException exception)
    {
    System.out.println("Error writing to file");
    }

    System.exit(0);

    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Problem trying to add a new file each time, without overwriting the previous.

    Do you know about arrays? This code needs to be rewritten using arrays.

    Also when posting code, Please wrap your code with code tags:
    [code=java]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.
    If you don't understand my answer, don't ignore it, ask a question.

  3. The Following User Says Thank You to Norm For This Useful Post:

    ArcherGilly (February 22nd, 2014)

  4. #3
    Junior Member
    Join Date
    Feb 2014
    Posts
    5
    My Mood
    Fine
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Problem trying to add a new file each time, without overwriting the previous.

    Norm, I know a little bit about arrays, but my programming experience is very low.

    would I put
    q1 = answer1.getText();
    q2 = answer2.getText();
    q3 = answer3.getText();
    q4 = answer4.getText();
    q5 = answer5.getText();
    q6 = answer6.getText();
    q7 = answer7.getText();
    q8 = answer8.getText();
    q9 = answer9.getText();
    q10 = answer10.getText();
    into an array, but that would just make it prettier though, wouldn't it.

    What array would I use (treeset, map or hashset)?

    Would putting it into an array solve my problem?

  5. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Problem trying to add a new file each time, without overwriting the previous.

    For example to use arrays:
    String[] q = new String[10];
    TheAnswerType[] answers = new TheAnswerType[10];

    A new file would be created by generating a new filename before each file is opened.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #5
    Junior Member
    Join Date
    Feb 2014
    Posts
    5
    My Mood
    Fine
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Problem trying to add a new file each time, without overwriting the previous.

    That is the problem I am having, trying to create a new file every time the program is run and the submit button is pressed. I would like to theoretically take all the answers and have it sent to an email address (that is way beyond my skills) instead.

    I would like students to anonymously answer the 10 questions and when they press the submit button, the answers are collated and sent to a folder, where I can then extract the data and input into excel, but not overwrite the previous file.

  7. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Problem trying to add a new file each time, without overwriting the previous.

    If you want to write to a new file every time, use the File class's exists()method to determine if there already is a file with the currently chosen name. If there is a file, change the name and test again. Put that code in a loop that keeps creating new names and testing if they exist. Exit the loop when a name has been found for a file that does not exist.
    If you don't understand my answer, don't ignore it, ask a question.

  8. The Following User Says Thank You to Norm For This Useful Post:

    ArcherGilly (February 23rd, 2014)

  9. #7
    Member
    Join Date
    Dec 2013
    Posts
    40
    My Mood
    Amazed
    Thanks
    2
    Thanked 11 Times in 11 Posts

    Default Re: Problem trying to add a new file each time, without overwriting the previous.

    It will be wise you name your files as so:
    Q1, Q2, Q3, etc. This should enable you use the isExist() method of the File class as a condition in a while loop while incrementing the numbers in the file names as Norm rightly mentioned.
    Who holds the KEY to all knowledge?

  10. The Following User Says Thank You to Mugambbo For This Useful Post:

    ArcherGilly (February 23rd, 2014)

  11. #8
    Junior Member
    Join Date
    Feb 2014
    Posts
    5
    My Mood
    Fine
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Problem trying to add a new file each time, without overwriting the previous.

    Thank you both for your help, I have decided to change it slightly so instead of creating new files each time, is to append to the original seperated by astrixis. If you have the time, would you be able to give me a small sample of how to input my answers into an array and iterate through them so they are written on the same document like I have done.

    package questionaire;
     
    import java.io.*;
    import java.nio.charset.Charset;
    import java.nio.file.Files;
    import java.nio.file.OpenOption;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.StandardOpenOption;
     
    /**
     *
     * @author David Gilligan 21/02/2014
     */
    public class recruitingQuestionaire extends javax.swing.JFrame
    {
     
        /**
         * Creates new form recruitingQuestionaire
         */
        public recruitingQuestionaire()
        {
            initComponents();
        }
     
        /**
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents()
        {
     
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            answer1 = new javax.swing.JTextField();
            jLabel3 = new javax.swing.JLabel();
            answer2 = new javax.swing.JTextField();
            jLabel4 = new javax.swing.JLabel();
            jLabel5 = new javax.swing.JLabel();
            jLabel6 = new javax.swing.JLabel();
            jLabel7 = new javax.swing.JLabel();
            jLabel8 = new javax.swing.JLabel();
            jLabel9 = new javax.swing.JLabel();
            jLabel10 = new javax.swing.JLabel();
            jLabel11 = new javax.swing.JLabel();
            answer3 = new javax.swing.JTextField();
            answer4 = new javax.swing.JTextField();
            answer9 = new javax.swing.JTextField();
            answer6 = new javax.swing.JTextField();
            answer5 = new javax.swing.JTextField();
            answer7 = new javax.swing.JTextField();
            answer8 = new javax.swing.JTextField();
            answer10 = new javax.swing.JTextField();
            resetButton = new javax.swing.JButton();
            submitButton = new javax.swing.JButton();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
     
            jLabel1.setText("Recruitment Questionaire");
     
            jLabel2.setText("Q1. How old are you?");
     
            jLabel3.setText("Q2. What town are you from?");
     
            jLabel4.setText("Q3.");
     
            jLabel5.setText("Q9");
     
            jLabel6.setText("Q8");
     
            jLabel7.setText("Q6");
     
            jLabel8.setText("Q4.");
     
            jLabel9.setText("Q5.");
     
            jLabel10.setText("Q7");
     
            jLabel11.setText("Q10.");
     
            resetButton.setText("Reset Form");
            resetButton.addActionListener(new java.awt.event.ActionListener()
            {
                public void actionPerformed(java.awt.event.ActionEvent evt)
                {
                    resetButtonActionPerformed(evt);
                }
            });
     
            submitButton.setText("Submit Form");
            submitButton.addActionListener(new java.awt.event.ActionListener()
            {
                public void actionPerformed(java.awt.event.ActionEvent evt)
                {
                    submitButtonActionPerformed(evt);
                }
            });
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(answer10, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(33, 33, 33)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel3)
                                        .addComponent(jLabel2)
                                        .addComponent(jLabel4)
                                        .addComponent(jLabel8)
                                        .addComponent(jLabel9)
                                        .addComponent(jLabel7)
                                        .addComponent(jLabel10)
                                        .addComponent(jLabel6)
                                        .addComponent(jLabel5)
                                        .addComponent(jLabel11)))
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(51, 51, 51)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(answer2, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(answer1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(answer3, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(answer4, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(answer5, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(answer6, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(answer7, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(answer8, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(answer9, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(88, 88, 88)
                            .addComponent(resetButton)
                            .addGap(42, 42, 42)
                            .addComponent(submitButton)))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(jLabel1)
                    .addGap(94, 94, 94))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jLabel2)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(answer1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jLabel3)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(answer2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jLabel4)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(answer3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jLabel8)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(answer4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(5, 5, 5)
                    .addComponent(jLabel9)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(answer5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(3, 3, 3)
                    .addComponent(jLabel7)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(answer6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel10)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(answer7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel6)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(answer8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel5)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(answer9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jLabel11)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(answer10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(resetButton)
                        .addComponent(submitButton)))
            );
     
            pack();
        }// </editor-fold>
     
        private void resetButtonActionPerformed(java.awt.event.ActionEvent evt)
        {
            answer1.setText("");
            answer2.setText("");
            answer3.setText("");
            answer4.setText("");
            answer5.setText("");
            answer6.setText("");
            answer7.setText("");
            answer8.setText("");
            answer9.setText("");
            answer10.setText("");
     
        }
     
        private void submitButtonActionPerformed(java.awt.event.ActionEvent evt)
        {
            String q1,q2,q3,q4,q5,q6,q7,q8,q9,q10;
            q1 = answer1.getText();
            q2 = answer2.getText();
            q3 = answer3.getText();
            q4 = answer4.getText();
            q5 = answer5.getText();
            q6 = answer6.getText();
            q7 = answer7.getText();
            q8 = answer8.getText();
            q9 = answer9.getText();
            q10 = answer10.getText();
     
            Path newFile = Paths.get("C:/Users/David/Desktop/programming/questionaire/Files/Questionaires.txt");
     
            try
            {
               newFile = Files.createFile(newFile);
            }
            catch (IOException e)
            {
                System.out.println("Error Creating File!");
            }
            System.out.println(Files.exists(newFile));
     
            try(BufferedWriter writer = Files.newBufferedWriter(newFile,Charset.forName("UTF-8"),new OpenOption[] {StandardOpenOption.APPEND}))
            {
                writer.append(q1);
                writer.newLine();
                writer.append(q2);
                writer.newLine();
                writer.append(q3);
                writer.newLine();
                writer.append(q4);
                writer.newLine();
                writer.append(q5);
                writer.newLine();
                writer.append(q6);
                writer.newLine();
                writer.append(q7);
                writer.newLine();
                writer.append(q8);
                writer.newLine();
                writer.append(q9);
                writer.newLine();
                writer.append(q10);
                writer.newLine();
                writer.append("************************");
                writer.newLine();
                writer.flush();
            }
            catch(IOException exception)
            {
                System.out.println("Error writing to file");
            }
     
            System.exit(0);
     
     
        }
     
        /**
         * @param args the command line arguments
         */
        public static void main(String args[])
        {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see [url]http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html[/url] 
             */
            try
            {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
                {
                    if ("Nimbus".equals(info.getName()))
                    {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            }
            catch (ClassNotFoundException ex)
            {
                java.util.logging.Logger.getLogger(
                        recruitingQuestionaire.class.getName()).log(
                        java.util.logging.Level.SEVERE, null, ex);
            }
            catch (InstantiationException ex)
            {
                java.util.logging.Logger.getLogger(
                        recruitingQuestionaire.class.getName()).log(
                        java.util.logging.Level.SEVERE, null, ex);
            }
            catch (IllegalAccessException ex)
            {
                java.util.logging.Logger.getLogger(
                        recruitingQuestionaire.class.getName()).log(
                        java.util.logging.Level.SEVERE, null, ex);
            }
            catch (javax.swing.UnsupportedLookAndFeelException ex)
            {
                java.util.logging.Logger.getLogger(
                        recruitingQuestionaire.class.getName()).log(
                        java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
     
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable()
            {
                public void run()
                {
                    new recruitingQuestionaire().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify
        private javax.swing.JTextField answer1;
        private javax.swing.JTextField answer10;
        private javax.swing.JTextField answer2;
        private javax.swing.JTextField answer3;
        private javax.swing.JTextField answer4;
        private javax.swing.JTextField answer5;
        private javax.swing.JTextField answer6;
        private javax.swing.JTextField answer7;
        private javax.swing.JTextField answer8;
        private javax.swing.JTextField answer9;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel10;
        private javax.swing.JLabel jLabel11;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JLabel jLabel4;
        private javax.swing.JLabel jLabel5;
        private javax.swing.JLabel jLabel6;
        private javax.swing.JLabel jLabel7;
        private javax.swing.JLabel jLabel8;
        private javax.swing.JLabel jLabel9;
        private javax.swing.JButton resetButton;
        private javax.swing.JButton submitButton;
        // End of variables declaration
    }

  12. #9
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Problem trying to add a new file each time, without overwriting the previous.

    Solved then?

Similar Threads

  1. Very frustrating problem with writing to a file, cannot find file when overwriting.
    By lordofrandom in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: June 18th, 2013, 06:18 AM
  2. Replies: 0
    Last Post: January 28th, 2013, 05:29 AM
  3. How to Add JPanel to JFrame during run-time
    By patelramanna in forum AWT / Java Swing
    Replies: 2
    Last Post: December 12th, 2012, 08:32 PM
  4. Overwriting txt file
    By The_Mexican in forum What's Wrong With My Code?
    Replies: 3
    Last Post: November 29th, 2010, 08:21 AM
  5. Problem with overwriting a file using IO package
    By marksquall in forum File I/O & Other I/O Streams
    Replies: 6
    Last Post: March 28th, 2009, 06:37 AM