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

Thread: Need help with BufferedReader and BufferedWriter

  1. #1
    Member
    Join Date
    Sep 2012
    Posts
    56
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default Need help with BufferedReader and BufferedWriter

    So given an input file, input.txt. I am trying to write a program that will firstly: print each line from input.txt line by line as it appears in the text file. So lets say the text file says:

    This line first
    This line seccond

    Then when I print it should say:

    This line first
    This line seccond

    Secondly, I want to print such that the input text reads:

    This
    line
    first
    This
    line
    seccond

    Thirdly, I want to write to a file such that the output matches the input. So again if the input is:

    This line first
    This line seccond

    Then the output file (outputTextA in this case) should read:

    This line first
    This line seccond

    Here is my code for doing those first three steps and it works just fine:

    String inputFile = "src/input/input.txt";
            String outputFileA = "src/output/outputA.txt";
            String outputFileB = "src/output/outputB.txt";
            StringBuilder outputStringA = new StringBuilder();
     
            try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))){
     
                String line;
     
                while ((line = reader.readLine()) != null){
     
                    outputStringA.append(line);
     
                    if (line != null){
                        outputStringA.append(System.lineSeparator());
                    }
                }
     
                System.out.println(outputStringA);
     
            }catch(IOException x){
                System.err.format("IOException: %s%n", x);
            }
     
            String s1 = outputStringA.toString();
     
            for (String word : s1.split(" ")){
     
                System.out.println(word);
            }
     
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileA))){
     
                writer.write(s1, 0, outputStringA.length());
            }catch(IOException x){
                System.err.format("IOException: %s%n", x);
            }

    Now, I want to output to a file such that if the input text is:

    This line first
    This line seccond

    Then the output text would be:

    This
    line
    first
    This
    line
    seccond

    However, I cannot figure out how!

    I have tried many things none of which are working. I have tried:

    for (String word : s1.split(" ")) {
     
                try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileB))) {
     
                    writer.write(word, 0, outputStringA.length());
                } catch (IOException x) {
                    System.err.format("IOException: %s%n", x);
                }
            }

    However this throws and exception. I have also tried:

    try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileA))) {
                for (String word : s1.split(" ")) {
                    writer.write(word, 0, outputStringA.length());
     
                }
            } catch (IOException x) {
                System.err.format("IOException: %s%n", x);
            }

    However, this also throws and exception.

    There must be an easier way can someone please help me out?

    --- Update ---

    Just a quick note I also tried converting the string s1 into an array list. Then tried writting the array list to the file like this:

    List<String> myList = new ArrayList<String>(Arrays.asList(s1.split(" ")));

    Then although I was able to write the list into the file I could not figure out how to write the list into the file in the proper format.

  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: Need help with BufferedReader and BufferedWriter

    However, I cannot figure out how!
    Is the problem: How to split a String up into tokens that were separated by spaces?
    The String class's split method will do that.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Sep 2012
    Posts
    56
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default Re: Need help with BufferedReader and BufferedWriter

    Well I can split the string up into tokens separated by spaces. However, I can't seem to figure out how to then take each of those tokens and write them to a file. For instance, if the input file reads:

    This is a line
    another line

    Then I have figured out how to print in the console such that it prints each word in a new line using the split method like this:

    This
    is
    a
    line
    another
    line

    However, I can't seem to figure out how to write that same format to a file.

    --- Update ---

    The solution to me seems pretty simple. Just split it up in a loop and write each word to the file on a new line. However, when I try to do that the program throws an exception.

  4. #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: Need help with BufferedReader and BufferedWriter

    the program throws an exception.
    Please copy the full text of the error message and paste it here. It has important info about the error.

    I can split the string up into tokens separated by spaces. ... how to then take each of those tokens and write them to a file.
    Where are the tokens after they are separated?
    Can a loop access them one at a time and write each to its own line?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Sep 2012
    Posts
    56
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default Re: Need help with BufferedReader and BufferedWriter

    Okay here's my program as I think it should work:

    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    package lab1;
     
    import java.io.*;
    import java.util.Arrays;
     
    /**
     *
     * @author vysero
     */
    public class Lab1 {
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
     
            String inputFile = "src/input/input.txt";
            String outputFileA = "src/output/outputA.txt";
            String outputFileB = "src/output/outputB.txt";
            StringBuilder outputStringA = new StringBuilder();
     
            try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
     
                String line;
     
                while ((line = reader.readLine()) != null) {
     
                    outputStringA.append(line);
     
                    if (line != null) {
                        outputStringA.append(System.lineSeparator());
                    }
                }
     
                System.out.println(outputStringA);
     
            } catch (IOException x) {
                System.err.format("IOException: %s%n", x);
            }
     
            String s1 = outputStringA.toString();
     
            for (String word : s1.split(" ")) {
     
                System.out.println(word);
            }
     
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileA))){
     
                writer.write(s1, 0, outputStringA.length());
     
            } catch (IOException x) {
                System.err.format("IOException: %s%n", x);
            }
     
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileB))){
     
                for(String newS : s1.split(" ")){
     
                    writer.write(newS, 0, outputStringA.length());
                }
            } catch (IOException x) {
                System.err.format("IOException: %s%n", x);
            }
        }
    }

    Here is the error it throws:

    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 424
    at java.lang.String.getChars(String.java:809)
    at java.io.BufferedWriter.write(BufferedWriter.java:2 26)
    at lab1.Lab1.main(Lab1.java:65)
    Java Result: 1

  6. #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: Need help with BufferedReader and BufferedWriter

    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 424
    at java.lang.String.getChars(String.java:809)
    at java.io.BufferedWriter.write(BufferedWriter.java:2 26)
    at lab1.Lab1.main(Lab1.java:65)
    The code at line 65 used and index (424) past the end of the String.

    What is that line trying to do? What are the values being passed to the write method?

    Please read the API doc for the write() method to see what args it takes.
    If you don't understand my answer, don't ignore it, ask a question.

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

    vysero (January 19th, 2018)

  8. #7
    Member
    Join Date
    Sep 2012
    Posts
    56
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default Re: Need help with BufferedReader and BufferedWriter

    Quote Originally Posted by Norm View Post
    The code at line 65 used and index (424) past the end of the String.

    What is that line trying to do? What are the values being passed to the write method?

    Please read the API doc for the write() method to see what args it takes.
    You Sr. are a genius, thank you!

Similar Threads

  1. [SOLVED] Issues With BufferedReader
    By tyeeeee1 in forum File I/O & Other I/O Streams
    Replies: 0
    Last Post: December 1st, 2013, 09:49 PM
  2. BufferedWriter help
    By shen_punkz21 in forum What's Wrong With My Code?
    Replies: 11
    Last Post: March 3rd, 2013, 11:54 AM
  3. 'BufferedReader' problem...
    By Akarsh in forum Member Introductions
    Replies: 3
    Last Post: August 15th, 2011, 05:37 PM
  4. BufferedWriter Problem
    By dailywalker in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 4th, 2011, 10:44 PM
  5. BufferedReader
    By reg4ltip in forum What's Wrong With My Code?
    Replies: 2
    Last Post: November 20th, 2010, 12:15 PM