|
-
December 13th, 2011, 05:57 PM
#1
Help with .csv file to ArrayList
Hi,
Basically I am working on a uni project but I am pretty new to Java. I've been trying to figure out how to do this for days now but just can't get it right. Really need to get it done as the deadline is approaching!
I have 3 (large) tab delimited CSV files that I need the user to be able to search for data inside on a command line input. I'm planning to have a class for putting the CSV files into ArrayLists or another type and a class for handling user input for a start. Is this a good way to go about it?
The part I'm really struggling with is reading a CSV file into an ArrayList. Just can't seem to get my head around it or get it to work despite spending loads of time reading up on it.
I've been fiddling around with some code to try to get an idea of how to put the data into an ArrayList using the tokenizer. When trying to print the arraylist, it seems to show each item twice. I've used two classes, a data manager class and the main one to call it.
The code is like this for the data handling class.
Code:
public class DataManager {
String fileName;
ArrayList <String>storeValues = new ArrayList<String>();
public DataManager(String FileName)
{
this.fileName=FileName;
}
public void ReadFile()
{
try {
BufferedReader br = new BufferedReader( new FileReader(fileName));
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
while( (fileName = br.readLine()) != null)
{
lineNumber++;
System.out.println(fileName);
storeValues.add(fileName);
//break comma separated line using ","
st = new StringTokenizer(fileName, "\t");
while(st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
//reset token number
tokenNumber = 0;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//mutators and accesors
public void setFileName(String newFileName)
{
this.fileName=newFileName;
}
public String getFileName()
{
return fileName;
}
public ArrayList getFileValues()
{
return this.storeValues;
}
public void displayArrayList()
{
for(int x=0;x<this.storeValues.size();x++)
{
System.out.println(storeValues.get(x));
}
}
Main class:
Code:
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String fileName="path to my csv file";
DataManager x=new DataManager(fileName);
x.ReadFile();
x.displayArrayList();
}
}
Any help on this would be great. Also, how would I go about searching for an item using data from more than one ArrayList (from the csv files)? I will be using a scanner to get user input for the word to search and then show data from the class.
Thanks.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|