-
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
-
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
-
Re: Read Text File Into Strings
Hi, thanks for that I will try that.
I have been messing around with the following code
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
-
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 :P
You're free to go your own way, but Scanner might be best.
-
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
-
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.
Code java:
public List<String> getList(List<String> list){
//read file
//get file content
list.add("file content goes here");
return list;
}
-
Re: Read Text File Into Strings
Quote:
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?
-
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
-
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.
-
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
-
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.
-
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
Code :
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
-
Re: Read Text File Into Strings
Quote:
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.
-
Re: Read Text File Into Strings
Note: Be careful when coding such things as:-
Code java:
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
-
Re: Read Text File Into Strings
Thanks, I got it working =).
-
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
-
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.
-
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
-
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?
-
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.
-
Re: Read Text File Into Strings
Quote:
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
-
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.
Code :
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.
-
Re: Read Text File Into Strings
Does it do what you want?
-
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
-
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.