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.

Page 1 of 2 12 LastLast
Results 1 to 25 of 32

Thread: Read Text File Into Strings

  1. #1
    Member
    Join Date
    Dec 2011
    Posts
    38
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Read Text File Into Strings

    Hi, I need to be able to read in a .csv file with a few columns into strings.

    e.g.
    myFile.csv

    Name, surname, age
    a, b, 5
    b, c, 20
    etc

    If the file has say 50 rows, i want to perform the particular operation 50 times (i could use a for loop of something for this)

    Could someone point me in the right direction to what i need to do to read in text file data into a string.

    Many thanks


  2. #2
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    661
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Read Text File Into Strings

    Look at using the Scanner class and applying a comma as the delimiter.
    I suggest you read through the API to understand what needs to be done.

    Meanwhile, here's a tutorial on the basics of using the Scanner class.
    http://www.javaprogrammingforums.com...ner-class.html
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  3. #3
    Member
    Join Date
    Dec 2011
    Posts
    38
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Read Text File Into Strings

    Hi, thanks for that I will try that.

    I have been messing around with the following code

    class FileRead 
    {
     public static void main(String args[])
      {
      try{
      // Open the file that is the first 
      // command line parameter
      FileInputStream fstream = new FileInputStream("textfile.txt");
      // Get the object of DataInputStream
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;
      //Read File Line By Line
      while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
      System.out.println (strLine);
      }
      //Close the input stream
      in.close();
        }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
      }
      }
    }

    would this be appropriate, does it have any advantages / disadvantages over the scanner class method you suggested?

    thanks

  4. #4
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    661
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Read Text File Into Strings

    My own instinct would to go with the Scanner class, due to having simple ways of parsing primitives (i.e. nextInt() etc) for your problem.
    Along with the aesthetic bonus of a lot less code

    You're free to go your own way, but Scanner might be best.
    Last edited by newbie; January 6th, 2012 at 05:54 AM.
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  5. #5
    Member
    Join Date
    Dec 2011
    Posts
    38
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Read Text File Into Strings

    yea i have just been messing around with scanner and it seems a lot easier, thank you for that.

    I am new to Java, but is there a way in which i can pass a arraylist into a class i have created (that reads in files and puts the data into strings and adds it to a list), and add the list to the arraylist that was sent in and then return it back.

    thanks

  6. #6
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    661
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Read Text File Into Strings

    Here is an example of a method which would take a List of Strings as parametrised input, then add a String to it, then return that list.
    	public List<String> getList(List<String> list){
    		//read file
    		//get file content
    		list.add("file content goes here");
    		return list;
    	}
    Last edited by newbie; January 6th, 2012 at 06:59 AM.
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  7. #7
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Read Text File Into Strings

    I am new to Java, but is there a way in which i can pass a arraylist into a class i have created (that reads in files and puts the data into strings and adds it to a list), and add the list to the arraylist that was sent in and then return it back.
    Pardon???? What did you mean?

  8. #8
    Member
    Join Date
    Dec 2011
    Posts
    38
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Read Text File Into Strings

    Sorry about the confusion.

    Basically i've created a class called movie (which is like a type).
    from the movie I have created a class which uses the movie class to make a movielist object (of the type movie). This class has all the functions for adding deleting, modifying etc movies in the movielist, this is done manually with user input.

    I now need to be able to add movies to the movielist by using data in a text file. I have created a class that can read in data and store it into strings, which are then added to an object of the type movie, this movie object is then added to a movielist object. I need the movielist object used in other parts of my program to be the same as the one used in the class that read in data and stores it

    does that make any sense?

    thanks
    Last edited by Khadafi; January 6th, 2012 at 10:35 AM.

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,149
    Thanks
    48
    Thanked 2,158 Times in 2,131 Posts

    Default Re: Read Text File Into Strings

    If you only create ONE instance of an arraylist, you can pass references to that one instance to many different methods which can add and change entries in that one arraylist.

  10. #10
    Member
    Join Date
    Dec 2011
    Posts
    38
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Read Text File Into Strings

    Hi, how would I do that, I know how to do it in C++, but I am new to java Could you please give me enable example.

    Thank you

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,149
    Thanks
    48
    Thanked 2,158 Times in 2,131 Posts

    Default Re: Read Text File Into Strings

    In C++ you could create many pointers that point to one object created with a new statement.
    Same in Java. Create the arraylist and save its address in a pointer. Pass that pointer to any method that wants access to the object. In Java I call the pointers, reference variables. Basically the same as a pointer.

    AClass aRef = new AClass(); // create an instance of an object and save its address in aRef
    classRef.someMethod(aRef); // pass aRef(refers to AClass object) to someMethod in the classRef object.

  12. #12
    Member
    Join Date
    Dec 2011
    Posts
    38
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Read Text File Into Strings

    Hi, thanks for that, got that part working where i sent in a variable from another class.

    but now, I am facing a problem where whatever is the last data row of the file, is appearing for all data rows in the arraylist

     try {
     
                Scanner scanner = new Scanner(file);
                scanner.useDelimiter(",|\n");
     
                Person data1 = new Person(); // creates a new person object
     
                //while (scanner.hasNextLine()) {
     
                	while (scanner.hasNext()) {
                		//System.out.println(scanner.next());
                		//myMovieList.clear();
                		String Name = scanner.next();
                		String Surname = scanner.next();
                		String Age = scanner.next();
     
                    	// set attributes for person
                    	person1.setName(Name);
                    	person1.setSurname(Surname);
                    	person1.setAge(Age);
     
                		// add person to person list
                		myPersonList.add(person1);	// myPersonList is sent into the function
                	}        		
              //  }            
                scanner.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }  
        }
    }

    after this when i am using myPersonList in another class, it contains the correct number of data and in the right format etc, but the data is the same in every single one.

    for example in my csv:
    name, surname, age
    x, , y , 6
    y, , y , 9
    z, , y , 8
    a, , y , 5
    b, , y , 7

    the arraylist (myPersonList) has the correct number of data rows but every single one contains b, y, 7 and not the others.

    Thanks

  13. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,149
    Thanks
    48
    Thanked 2,158 Times in 2,131 Posts

    Default Re: Read Text File Into Strings

    whatever is the last data row of the file, is appearing for all data rows in the arraylist
    That sounds like there is only one object and all the references in the arraylist point/refer to that one object. Be sure you create a new object to hold the new data before you put it into the arraylist.

  14. #14
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    661
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Read Text File Into Strings

    Note: Be careful when coding such things as:-
    while (scanner.hasNext()) {
           String Name = scanner.next();
           String Surname = scanner.next();
    }

    because hasNext() only checks to see whether a single token is ahead and available, so hasNext() might be true for the .next() call @ Name, but might not be true for Surname.
    If that makes sense :3
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  15. #15
    Member
    Join Date
    Dec 2011
    Posts
    38
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Read Text File Into Strings

    Thanks, I got it working =).

  16. #16
    Member
    Join Date
    Dec 2011
    Posts
    38
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Read Text File Into Strings

    Hi, I need to create another scanner to take in data in the format

    A Name (2009) 2009
    Another Name (2011) 2011
    ..etc that are stored in a list file

    I need the name 'A Name' to be stored in one string,
    and any one of the years '2009' to be stored in another string

    how would i create a delimiter to do that and would i use scanner has next line or scanner . next, (i have tried so many different things but it dosnt do what i need it to).

    Thanks

  17. #17
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,149
    Thanks
    48
    Thanked 2,158 Times in 2,131 Posts

    Default Re: Read Text File Into Strings

    Is the pattern like this:
    <PART1> (<Part2>) <Part3>
    and you want to parse the String into those three parts?
    The String method indexOf would be very easy to use.

  18. #18
    Member
    Join Date
    Dec 2011
    Posts
    38
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Read Text File Into Strings

    the data is in a file, and is just text (like a txt file)
    A Name (2009) 2009

    i want to read in the data with the scanner (and then assign what is read in into String variables),
    i have done the same thing for a different data format that had a ',' to seperate each part of data so i used the ',' as a delimter and it worked, I dont know what to use as a delimiter for this as there is no ',' seperating the data.

    thanks

  19. #19
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,149
    Thanks
    48
    Thanked 2,158 Times in 2,131 Posts

    Default Re: Read Text File Into Strings

    Does the '(' separate the first part from the second part and the ')' separate the second part from the third part?

  20. #20
    Member
    Join Date
    Dec 2011
    Posts
    38
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Read Text File Into Strings

    Hi, yes that is what I was trying but didn't know how to write the delimiter for that.

    Thanks.

  21. #21
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,149
    Thanks
    48
    Thanked 2,158 Times in 2,131 Posts

    Default Re: Read Text File Into Strings

    how to write the delimiter
    You need a regular expression expert for that.
    You want either a left paran or right paran as the delimiters. I don't know if the their order is important. What if the data was: first part) second part (third part

  22. #22
    Member
    Join Date
    Dec 2011
    Posts
    38
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Read Text File Into Strings

    Hi, thanks.

    I am trying a different way as the other way is just confusing me.
    With this new way i think i am closer as i have the data split to the way i want it.

                while (scanner.hasNextLine()) {
     
                	String theNextLine = scanner.nextLine();	// set the next line to a string
     
                    String regex = "(\\(|\\)|\\/)";
                    String fields[] = theNextLine.split(regex);
     
                    for(String s: fields)
                    System.out.println("<"+s.trim()+">");

    what this does is read the next line and assign it to String theNextLine.
    String theNextLine is then split, when printed out it looks like this:
    <Name>
    <Year>
    <Year>
    which means it is splliting it perfectly as i want it to.

    but now i need to be able to assign the Name and Year contents to strings,
    Sting theName = ...;
    String theYear = ...;
    how would i take out the Name and Year data seperetly from the s.trim().

    Hope that makes sense, thanks.

  23. #23
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,149
    Thanks
    48
    Thanked 2,158 Times in 2,131 Posts

    Default Re: Read Text File Into Strings

    Does it do what you want?

  24. #24
    Member
    Join Date
    Dec 2011
    Posts
    38
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Read Text File Into Strings

    In a way as it can recognise and split the line into the 3.parts, but I just want to seperate the 3 parts and store each in a String?

    Thanks

  25. #25
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,149
    Thanks
    48
    Thanked 2,158 Times in 2,131 Posts

    Default Re: Read Text File Into Strings

    Please explain what the problem with the code is now?
    What do you want different from what it is now doing?
    The 3 parts are each in a String.

Page 1 of 2 12 LastLast

Similar Threads

  1. What is the best way to read from a text file?
    By Kerr in forum File I/O & Other I/O Streams
    Replies: 20
    Last Post: January 4th, 2012, 04:41 PM
  2. Read text file
    By cardamis in forum Java IDEs
    Replies: 2
    Last Post: November 4th, 2011, 11:59 PM
  3. Replies: 8
    Last Post: March 25th, 2011, 02:34 PM
  4. Read a text file and parse the contents of file
    By HelloAll in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: March 3rd, 2011, 04:47 AM
  5. reading content of the text file, splitting it into strings
    By Dodo in forum File I/O & Other I/O Streams
    Replies: 7
    Last Post: January 6th, 2011, 06:57 PM