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 2 of 2

Thread: Beginner I/O Help: Writing To a Text File At the End of Existing Lines of Text

  1. #1
    Junior Member
    Join Date
    Feb 2012
    Posts
    10
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Beginner I/O Help: Writing To a Text File At the End of Existing Lines of Text

    Hello all. This is my first post in this forum. I am in the second semester of a college Java class, so I'm pretty new. I just finished my first project on I/O. Unfortunately, the professor in this class has a habit of making assignments without first presenting the material, so on a new topic I sometimes get a bit lost trying to scour the internet for information that is relevant to my level of experience. We don't have a regular textbook that we follow either, so I cannot look to that for help.

    My issue now is that I just had a lab due (which Ive already submitted, so this is not cheating) that asked us to do the following:

    Have a file containing a few lines of questions, one on each line, that can be answered in one word. Like this:

    How old are you?
    What is your name?
    What is the weight of a cat on Veda?

    Our program was supposed to display each line one by one and let the user type in an answer, saving the answer on the same line as the question.

    How old are you? 5
    What is your name? Merriwether
    What is the weight of a cat on Veda? 83_vlerps

    At startup, the program was supposed to offer options to either open and print an existing file with the questions already answered, or answer the questions in a file. The question and answer were supposed to be on the same line so they could be split apart at the question mark and printed on separate lines if the user chose option 1.

    How old are you?
    5
    What is your name?
    Merriwether
    What is the weight of a cat on Veda?
    83_vlerps

    So I pieced together a program with what I read online, but I'm really a bit lost. It's a really messy program, and there were some things I was not able to do. One thing is that I was not able to save the data in the same file that I was reading, because the PrintWriter object deletes everything that is in the destination file when it is opened (I think). So I saved it to an output file, and then put in a convoluted renaming/deleting scheme that doesn't even work.

    Also, the split() method that was meant to break the question and answer apart to be printed on separate lines doesn't seem to work either.

    Can anyone offer some guidance on how this program should be written, while keeping at the same basic level?

    Thanks to everyone for sharing their knowledge.

    import java.util.*;
    import java.io.*;
     
    public class Lab5
    {
        public static void main(String[] args) throws IOException, FileNotFoundException
        {
            int choice;
            String location;
     
            Scanner input = new Scanner(System.in);
     
            System.out.println("Let's answer some questions.");
            do
            {
                System.out.println("Would you like to open answers from a previously saved file? Enter 1 for yes and 2 for no: ");
                choice = input.nextInt();
            }while (choice != 1 && choice != 2);
     
            if (choice == 1)
            {
                System.out.println("Please enter the file and path: ");
                location = input.next();
                File answers = new File(location);
                if (!answers.exists())
                {
                    System.out.println("File not found.");
                    choice = 2;
                }
                printAnswers(answers);
            }//end if
            else
            {
                System.out.println("That's okay, you can answer my questions.");
                location = "c:/BlueJ/mine/questions.txt";
                File questions = new File(location);
                if (!questions.exists())
                {
                    System.out.println("File not found.");
                    System.exit(0);
                }    
                answerQuestions(questions);
            }
     
     
        }//end main
        public static void printAnswers(File answers) throws IOException
        {
            Scanner fileReader = new Scanner(answers);
            while (fileReader.hasNext())
            {
                String line = fileReader.nextLine();
                String[] ln = line.split("?");
                System.out.println(ln[0] + "?");
                System.out.println(ln[1]);
     
            }//end while
        }//end method    
        public static void answerQuestions(File questions) throws IOException, FileNotFoundException
        {
            String answer;
            Scanner input = new Scanner(System.in);
            Scanner fileReader = new Scanner(questions);
            File outputFile = new File("c:\\BlueJ\\mine\\outputFile.txt");
            PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)));    
     
            while (fileReader.hasNext())
            {
                String line = fileReader.nextLine();
                System.out.println(line);
                answer = input.next();      
                line = line.concat(" " + answer);
                writer.println(line);
            }
            writer.flush();
            writer.close();
     
            boolean rn1 = questions.renameTo(new File("c:\\BlueJ\\mine\\answers.txt"));
            boolean rn2 = outputFile.renameTo(new File("c:\\BlueJ\\mine\\questions.txt"));
            if (rn1 && rn2)
            {
                File file = new File("c:\\BlueJ\\mine\\answers.txt");
                boolean deleted = file.delete();
                if (deleted)
                    System.out.println("Questions file altered.");
                else
                    System.out.println("Original file could not be altered. A new file, answers.txt, was created.");
            }
            else
                System.out.println("Original file could not be altered. A new file, outputFile.txt, was created.");
     
     
        }
    }


  2. #2
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: Beginner I/O Help: Writing To a Text File At the End of Existing Lines of Text

    the PrintWriter object deletes everything
    Read the PrintWriter documentation again. Its constructors hide a lot of implementation details, but it does say that it creates the necessary OutputStreamWriter, which can only be constructed on an OutputStream, and the subclass of OutputStream that works with Files is FileOutputStream, which has a constructor that allows you to append to an existing file.

    For your split problem you need to Read The Free Manual again - this time at String.split(String) and notice that its argument has a funny name: "regex". Click the link to read the detail of the method and see the link "regular expression". Follow *that* link to the doc for java.util.regex.Pattern and read copious amounts of very well written documentation until you see why "?" as a split regex may not give you what you expect.

Similar Threads

  1. Help writing to a text file on a website!
    By straw in forum File I/O & Other I/O Streams
    Replies: 10
    Last Post: September 11th, 2011, 11:02 AM
  2. Issues with writing to text file
    By surfbumb in forum What's Wrong With My Code?
    Replies: 2
    Last Post: May 12th, 2011, 09:43 AM
  3. Writing to a specific line in a text file
    By The_Mexican in forum What's Wrong With My Code?
    Replies: 2
    Last Post: January 7th, 2011, 09:11 PM
  4. Reading lines of a text file into a string array
    By fortune2k in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: November 11th, 2010, 11:56 AM
  5. Reading a lines from text file
    By kiran in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: September 26th, 2010, 10:54 PM