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

Thread: Reading lines of a text file into a string array

  1. #1
    Member
    Join Date
    Oct 2010
    Posts
    61
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Reading lines of a text file into a string array

    Hi Guys,

    I currently have this code

     
       public static void ReadFile2String(String InputFile)
        {
         try{
            FileInputStream fstream = new FileInputStream(InputFile);
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
     
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line
            text = "";
                while ((strLine = br.readLine()) != null) //loop through each line
                {
                // Print the content on the console
                text +=(strLine+"\n");  // Store the text file in the string
                }
            in.close();//Close the input stream
            }
            catch (Exception e)
            {//Catch exception if any
            System.out.println("Error: " + e.getMessage());
            }
        }
     
    }


    and what the code does above is basically reads in a text file line by line and stores all its contents in a sing String named text.

    What i want it to do is it to store each line into an undefinied string array however im getting no where. Do you guys have any suggestion of how i can alter the code above to have each line stored in a seperat part of the array for example

    test[2] = "the quick brown....."

    thankyou for all your help


  2. #2
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: Reading lines of a text file into a string array

    You will either need to declare the size of the array beforehand or use something like an ArrayList

    http://www.javaprogrammingforums.com...arraylist.html
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  3. #3
    Junior Member
    Join Date
    Nov 2010
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Reading lines of a text file into a string array

    What about to store it in a Vector

    like this....

    import java.util.Vector;
     
    public static void ReadFile2String(String InputFile)
        {
         try{
            FileInputStream fstream = new FileInputStream(InputFile);
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
     
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line
            text = "";
            Vector myVector = new Vector();
                while ((strLine = br.readLine()) != null) //loop through each line
                {
                 myVector.add(strLine );
                // Print the content on the console
                text +=(strLine+"\n");  // Store the text file in the string
     
                }
            in.close();//Close the input stream
           int i=0;
           for(i=0;i<myVector.size();i++){
                System.out.println("Position "+ i+" "+myVector.elementAt(i));
            }
     
     
            }
            catch (Exception e)
            {//Catch exception if any
            System.out.println("Error: " + e.getMessage());
            }
        }
     
    }

  4. #4
    Junior Member
    Join Date
    Nov 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Reading lines of a text file into a string array

    Have a look at the Java class StringBuilder.

    I beleive this will help you with what you are trying to achive.

    When you have created an instance of StringBuilder use the append method to append your line to the string and if you want a new line after each line of text just do this.

    mystringbuilder.append(lineFromFile + "\n");

    Then when you are done you can use mystringbuilder.toString(); to return the entire string.

    I forgot to mention check this link for the JavaDoc's on StringBuilder StringBuilder (Java 2 Platform SE 5.0)

    Enjoy
    Last edited by chegers; November 11th, 2010 at 07:39 AM. Reason: Added link

  5. #5
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Reading lines of a text file into a string array

    Quote Originally Posted by generalitico View Post
    What about to store it in a Vector

    like this....

    import java.util.Vector;
     
    public static void ReadFile2String(String InputFile)
        {
         try{
            FileInputStream fstream = new FileInputStream(InputFile);
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
     
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line
            text = "";
            Vector myVector = new Vector();
                while ((strLine = br.readLine()) != null) //loop through each line
                {
                 myVector.add(strLine );
                // Print the content on the console
                text +=(strLine+"\n");  // Store the text file in the string
     
                }
            in.close();//Close the input stream
           int i=0;
           for(i=0;i<myVector.size();i++){
                System.out.println("Position "+ i+" "+myVector.elementAt(i));
            }
     
     
            }
            catch (Exception e)
            {//Catch exception if any
            System.out.println("Error: " + e.getMessage());
            }
        }
     
    }
    More of a pet-peeve than anything else, but usually when you declare a List (you have used a Vector in this case) you want to specify what type of Objects are in that list. This is just a way to make it easier to access the Objects, as you will not need to cast the objects when you get them. This is not as much of an issue when you use Lists of Strings, as they are easy to cast since their Object Representation is just a String of its value (sort of odd, and I'm unsure how to explain it).

    However, this does become a problem if you had a Vector of Objects other than Strings. For example, a Vector of JFrames.
    If you declared your Vector using the way you did: Vector myVector = new Vector();, you would access the JFrames by saying:
    JFrame frame = (JFrame)myVector.get(0);
    Alternatively, if you declared your Vector to be restricted to only a Vector of JFrames like this: Vector<JFrame> myVector = new Vector<JFrame>();, you would access the JFrames by saying:
    JFrame frame = myVector.get(0);


    So, the more acceptable way of creating your Vector above (acceptable meaning the general consensus of the programming community) would be saying:
    Vector<String> myVector = new Vector<String>();


    Once again, sort of a moot point when you have a Vector of Strings, but it is good advise to have on the back-burner for your future data structures. Tell me if I am unclear.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  6. The Following User Says Thank You to aussiemcgr For This Useful Post:

    generalitico (November 11th, 2010)

Similar Threads

  1. 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
  2. [SOLVED] Reading from a text file and storing in arrayList
    By nynamyna in forum What's Wrong With My Code?
    Replies: 2
    Last Post: April 26th, 2010, 09:55 PM
  3. [SOLVED] reading only certain lines from a .txt file
    By straw in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: March 7th, 2010, 07:49 PM
  4. Reading from a text file. Help needed urgently.
    By TheAirPump in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: December 14th, 2009, 06:16 PM
  5. Reading from a file, multiple lines
    By MysticDeath in forum File I/O & Other I/O Streams
    Replies: 5
    Last Post: October 15th, 2009, 02:40 AM