1,105,592 Community Members

Reading in a *.csv file and loading the data into an Array

Member Avatar
AQWst
Light Poster
34 posts since Jan 2005
Reputation Points: -2 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I would like to know any advice for creating a program that will read in a *.csv file and load the data into a 24 x 24 array for further processing. I am including a total of 48 records, so that you can see how the data looks and what I'll be working with.

1.000000,0.767801,0.370782,1.887500,0.817261,0.120824,0.178702,1.329200,0.128401,0.022936,0.009620,0.263158,0.088230,0.702998,0.160940,0.607977,0.169635,0.000956,0.009970,0.147252,0.856678,0.031328,0.025595,0.000522
1.302420,1.000000,0.482914,2.458320,1.064420,0.157364,0.232745,1.731180,0.167232,0.029872,0.012529,0.342742,0.114913,0.915598,0.209611,0.791841,0.220936,0.001245,0.012985,0.191783,1.115750,0.040803,0.033336,0.000680
Member Avatar
Phaelax
Practically a Posting Shark
880 posts since Mar 2004
Reputation Points: 52 [?]
Q&As Helped to Solve: 54 [?]
Skill Endorsements: 4 [?]
 
0
 

I don't know what a csv file is or what the structure is, but if its just a text a file with numbers like that, it's quite simple.

The only thing to be careful about in this code is that it assumes there won't be more than 24 elements, or tokens, in each line of text.

String[24][24] numbers;
 
File file = new File("something.csv");
 
BufferedReader bufRdr  = new BufferedReader(new FileReader(file));
String line = null;
int row = 0;
int col = 0;
 
//read each line of text file
while((line = bufRdr.readLine()) != null)
{
	StringTokenizer st = new StringTokenizer(line,",");
	while (st.hasMoreTokens())
	{
		//get next token and store it in the array
		numbers[row][col] = st.nextToken();
		col++;
	}
	row++;
}
 
//close the file
bufRdr.close();
Member Avatar
AQWst
Light Poster
34 posts since Jan 2005
Reputation Points: -2 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Thanks for the help. I only had to change the program slightly with changes to the logic for it to work properly. (Please see my code to see what I did).

String [][] numbers = new String [24][24];
 
	File file = new File("Currency Exchange Rates.csv");
 
	BufferedReader bufRdr  = new BufferedReader(new FileReader(file));
	String line = null;
	int row = 0;
	int col = 0;
 
	//read each line of text file
	while((line = bufRdr.readLine()) != null && row < 24)
	{	
	StringTokenizer st = new StringTokenizer(line,",");
	while (st.hasMoreTokens())
	{
		//get next token and store it in the array
		numbers[row][col] = st.nextToken();
		col++;
	}
	col = 0;
	row++;
	}

:)

Member Avatar
chackboom
Newbie Poster
8 posts since Apr 2006
Reputation Points: -7 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
-1
 

I don't know what a csv file is or what the structure is, but if its just a text a file with numbers like that, it's quite simple.

The only thing to be careful about in this code is that it assumes there won't be more than 24 elements, or tokens, in each line of text.

String[24][24] numbers;
 
File file = new File("something.csv");
 
BufferedReader bufRdr  = new BufferedReader(new FileReader(file));
String line = null;
int row = 0;
int col = 0;
 
//read each line of text file
while((line = bufRdr.readLine()) != null)
{
	StringTokenizer st = new StringTokenizer(line,",");
	while (st.hasMoreTokens())
	{
		//get next token and store it in the array
		numbers[row][col] = st.nextToken();
		col++;
	}
	row++;
}
 
//close the file
bufRdr.close();

String field[] = line.split(",");

Member Avatar
stephen84s
Nearly a Posting Virtuoso
1,328 posts since Jul 2007
Reputation Points: 550 [?]
Q&As Helped to Solve: 160 [?]
Skill Endorsements: 13 [?]
Featured
 
0
 

@chackboom

Am pretty sure the O.P. must have found a solution to it long long ago, please check the dates before posting on such fossilized threads.

Member Avatar
rmkapil
Newbie Poster
1 post since Oct 2009
Reputation Points: -1 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

corrections in fossilized threads is certainly needed becuase those are still the source of information for many.

Member Avatar
darkknightgaury
Newbie Poster
4 posts since Oct 2006
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

The previous example breaks after col 25 because the array size reaches it limit.Here is a solution that does not depend on the arraysize

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.StringTokenizer;


public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String fileName="C:/Documents and Settings/tntadmin/workspace2/a.csv";
		try {
			BufferedReader br = new BufferedReader( new FileReader(fileName));
			String strLine = null;
			StringTokenizer st = null;
			int lineNumber = 0, tokenNumber = 0;
 
			while( (fileName = br.readLine()) != null)
			{
				lineNumber++;
 
				//break comma separated line using ","
				st = new StringTokenizer(fileName, ",");
 
				while(st.hasMoreTokens())
				{
					//display csv values
					tokenNumber++;
					System.out.println("Line # " + lineNumber + 
							", Token # " + tokenNumber 
							+ ", Token : "+ 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();
		}
	}

}
Member Avatar
darkknightgaury
Newbie Poster
4 posts since Oct 2006
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Here is my pimp code :)

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;


public class CSVFileReader {

	String fileName;
	
	 ArrayList <String>storeValues = new ArrayList<String>();
	public CSVFileReader(String FileName)
	{
		this.fileName=FileName;
	}
	
	public void ReadFile()
	{
		try {
			//storeValues.clear();//just in case this is the second call of the ReadFile Method./
			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, ",");

				while(st.hasMoreTokens())
				{	
					
					System.out.println("Line # " + lineNumber + 
							", Token # " + tokenNumber 
							+ ", Token : "+ 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));
		}
	}
	
}
public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String fileName="C:/Documents and Settings/tntadmin/workspace2/a.csv";
		CSVFileReader x=new CSVFileReader(fileName);
		x.ReadFile();
		x.displayArrayList();
	
	}

}
Member Avatar
darkknightgaury
Newbie Poster
4 posts since Oct 2006
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Feel free to comment and tell me how to make this better.

Member Avatar
heckyj
Newbie Poster
1 post since Jun 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Is there a way to print only a single line. Let's say that the a.csv files has 50 lines, how can I chose only line 20?

Member Avatar
mlehner616
Newbie Poster
1 post since Oct 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

just read the whole file into an array then echo the individual line you want. I'm a PHP programmer learning Java but I imagine the method is similar. (For those who look at this in the future)

//print just row 10
echo array[10];
daniwebkds
Newbie Poster
2 posts since Nov 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
Unverified Member
 
0
 

new StringTokenizer(fileName, ",")

daniwebkds
Newbie Poster
2 posts since Nov 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
Unverified Member
 
0
 

The problem with the above imlementation is that it uses StringTokenizer(fileName, ",") to break the line (initially) into a bunch of chunks. This approach does not work when there are commas is the string values. In that case, commas within the quotes have to be ignored, which the tokenizer does not do.

Let me refer you to a single class implementation that reads and write CSV files: The Only Class You Need for CSV Files:

http://agiletribe.wordpress.com/2012/11/23/the-only-class-you-need-for-csv-files/

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article