Help with file reading and data structures

How to read data from a file and store it in a data structure?

Page 1 of 1

7 Replies - 6937 Views - Last Post: 29 March 2008 - 09:13 AM Rate Topic: -----

#1 Java coder  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 26-March 08

Help with file reading and data structures

Post icon  Posted 26 March 2008 - 08:28 AM

Hi, I have a problem. I want to read data from a text file and store the data in a data structure when the user selects the input data option.

The text file reads like this:

Ferrari T12 Fiat 416 312-32-432 000 5000 3000 0 80
Camry C14 Toyota 512 312-77-111 000 9000 7000 0 90
Corolla C19 Toyota 812 312-77-022 001 9000 6000 0 70
..
..and so on


In this text file, Ferrari represents Product, T12 represents Model, Fiat represents Manufacturer, 416 is the type code, 312-32-432 is the ID number, 000 is location code, 5000 is maximum price, 3000 is unit cost, 0 is discount offered and 80 is stock quantity available.


I need to read this data from the file and then store it in a data structure. I also need to use sorting algorithm on the created data structure to sort according to the property the user chooses..for example if user says sort by Model, then the program should sort the contents of the data-structure(not the file) by Model attribute. I am confused as to which data structure to use(I can use only linked lists or arrays). Also, I dont know how to split the data in the text file and store in the data structure. Currently, I am able to read the file and output its contents to the user. However, I do not know how to store the data in a data structure so that it can be easily searched and sorted according to the attribute the user chooses.
Please help...

Is This A Good Question/Topic? 0
  • +

Replies To: Help with file reading and data structures

#2 spullen  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 10
  • View blog
  • Posts: 356
  • Joined: 22-March 07

Re: Help with file reading and data structures

Posted 26 March 2008 - 09:43 AM

sounds like a HW assignment. What specifically are you having trouble with, do you have code? Just a suggestion, but a google search for reading in text files would help you a lot, and same goes for data structures and how to use them.
Was This Post Helpful? 0
  • +
  • -

#3 Java coder  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 26-March 08

Re: Help with file reading and data structures

Posted 26 March 2008 - 10:32 AM

View Postspullen, on 26 Mar, 2008 - 09:43 AM, said:

sounds like a HW assignment. What specifically are you having trouble with, do you have code? Just a suggestion, but a google search for reading in text files would help you a lot, and same goes for data structures and how to use them.


well..this is what i have so far: when user selects default file..the program reads data from the default file [this button event is not responding btw..] and when user selects open another file, a dialog box opens to let the user choose which file he wants..then opens it in a text area on the input GUI window..

I am able to read the file..but i need to store it in a data structure. Since i'm not too comfortable with linked lists, i was thinking maybe to use a 2D array for storing row and column data..but am not too sure about the implementation. Using a class of objects is another choice..but am confused as to how to implement it. I don't want the code. I want to know the logic behind the code..
This is the class file which would be opened if user chooses input data option. I need to initialize a data structure in this class and then store the contents of the text file in it piecewise..

import java.io.*;

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Button;
import java.awt.Color;
import java.awt.Event;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;

public class Input extends Frame implements 
WindowListener,ActionListener
{
	public static Input in;
	  
	  
	  
	  Button but_default =new Button("Use Default File");
	  Button but_another=new Button("Open Another File");
	  RandomAccessFile raf;
	  FileOutputStream a;
	  FileDialog fd,f;
	  byte[] temp;
	  String s1,s2,s;
	  StringBuffer sb;
	  int x,y,d,l;
	  Font font=new Font("VinetaBT",Font.BOLD|Font.ITALIC,18);
	  TextArea ta=new TextArea();


	  
	  public Input()
	{
		super("Input Data");
		addWindowListener(this);
		setLayout(new GridLayout(12,1));
		setBackground(Color.orange);
		setForeground(Color.black);
		addMenu();
		x=550;
		y=450;
		d=100;
		setSize(x,y);
		show();
	}
	  
	  void addMenu()
	  {
			Panel p=new Panel();
			p.setLayout(new FlowLayout(FlowLayout.CENTER,5,5));
			Label l1= new Label("Welcome to Input Data Menu!");
			l1.setFont(font);
			p.add(l1,Label.LEFT);
			Panel p1=new Panel();
			p1.setLayout(new FlowLayout(FlowLayout.LEFT,5,5));
			Label l2= new Label("Please Choose the Data File to read from: ");
			l2.setFont(font);
			p1.add(l2,Label.LEFT);
			Panel p2=new Panel();
			p2.setLayout(new FlowLayout(FlowLayout.LEFT,10,10));
			p2.add(but_default);
			p2.add(but_another);
			but_default.addActionListener(this);
			but_another.addActionListener(this);
			Panel p3=new Panel();
			ta.setEditable(true);
			p3.add(ta);
			ta.setSize(350,300);
			p3.setLayout(new FlowLayout(FlowLayout.LEADING));
			add(p);
			add(p1);
			add(p2);
			add("South",p3);
	  }	  
		  
				  
	  
	  public void actionPerformed(ActionEvent e)
	  {
		  String arg=e.getActionCommand();
		  try
			{	
			if(e.getSource() instanceof Button)
				
					if("Use Default File".equals(arg))
				  {
					  raf=new RandomAccessFile("Default file.txt,"rw");
					repaint();
					ta.setEditable(false);
				  }
				  else if("Open Another File".equals(arg))
				  {
					fd=new FileDialog(this,"Opening an existing file",0);
					fd.setDirectory("C:/");
					fd.setFile("*.txt");
					fd.setVisible(true);
					s1=fd.getDirectory();
					s2=fd.getFile();
					raf=new RandomAccessFile(s1+s2,"rw");
					repaint();
					ta.setEditable(false);
				  }
			 }
			  catch(java.io.IOException e1)
			{ }
	  }
	 
	  public void windowClosed(WindowEvent we){}
	  public void windowDeiconified(WindowEvent we){}
	  public void windowIconified(WindowEvent we){}
	  public void windowActivated(WindowEvent we){}
	  public void windowDeactivated(WindowEvent we){}
	  public void windowOpened(WindowEvent we){}

	  public void windowClosing(WindowEvent we)
	   {
				   dispose();
	  }
	  
	  public void paint(Graphics g)
		{
			try
			{
				if(raf!=null)
				{
					l=(int)raf.length();
					System.out.println("raf is: "+l);
				}
				if(l!=0)
				{
					temp=new byte[l+1];
					raf.read(temp,0,l);
					sb=new StringBuffer();
					for(int i=0;i<l;i++)
						sb.append((char)temp[i]);
					s=sb.toString();
					ta.append(s);
				}
			}
			catch(java.io.IOException e2) { }
		}
 }


Was This Post Helpful? 0
  • +
  • -

#4 spullen  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 10
  • View blog
  • Posts: 356
  • Joined: 22-March 07

Re: Help with file reading and data structures

Posted 26 March 2008 - 12:05 PM

You need to find out how many elements are in each row and how many columns there are. That way you can initialize the size of the array. Then for each line that you get back parse each element and place it into the array within the array (2d array), so the index of the array would be someArray[row_of_line][x], where x is the index of the element in the row. (I'm assuming that the file is a bunch of lines with a bunch of data that you parse and each "token" is its own array location). I am pretty sure there is a much easier way to do this, other than the way you want. I would do a google search for reading files in and try to get a better idea of what can be done.
Was This Post Helpful? 0
  • +
  • -

#5 Java coder  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 26-March 08

Re: Help with file reading and data structures

Posted 26 March 2008 - 12:11 PM

View Postspullen, on 26 Mar, 2008 - 12:05 PM, said:

You need to find out how many elements are in each row and how many columns there are. That way you can initialize the size of the array. Then for each line that you get back parse each element and place it into the array within the array (2d array), so the index of the array would be someArray[row_of_line][x], where x is the index of the element in the row. (I'm assuming that the file is a bunch of lines with a bunch of data that you parse and each "token" is its own array location). I am pretty sure there is a much easier way to do this, other than the way you want. I would do a google search for reading files in and try to get a better idea of what can be done.

ok...I think I understand what you are talking about..it sounds complicated..right now, to go easy on myself, I am using command line interface..I am able to read the file and print it out on the console as it is..now i have to research how to parse it ..i want to use a data structure which would go easy on the sorting algorithm..I will do my research, but at the same time please do let me know if you come with something simpler..Thanks for your time!:-)
Was This Post Helpful? 0
  • +
  • -

#6 spullen  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 10
  • View blog
  • Posts: 356
  • Joined: 22-March 07

Re: Help with file reading and data structures

Posted 27 March 2008 - 01:48 PM

I would definitely invest some time in looking at data structures other then arrays. I would either go with a linked list or something that can have an arbitrary depth, since you don't know how much data that you have in the text file. I would actually use a tree, http://java.sun.com/...ge-summary.html, the tree in the Java API actually keeps the data sorted (I believe).
good luck.
Was This Post Helpful? 0
  • +
  • -

#7 Java coder  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 26-March 08

Re: Help with file reading and data structures

Posted 28 March 2008 - 02:34 PM

View Postspullen, on 27 Mar, 2008 - 01:48 PM, said:

I would definitely invest some time in looking at data structures other then arrays. I would either go with a linked list or something that can have an arbitrary depth, since you don't know how much data that you have in the text file. I would actually use a tree, http://java.sun.com/...ge-summary.html, the tree in the Java API actually keeps the data sorted (I believe).
good luck.


Well, I have decided to use an ArrayList..where I can store object of each type, say model, manufacturer, and so on into an array of its own type. But before I do that, I have to split the elements of the file into their respective categories. I have two options: use string tokenizer or use the split command. I'm able to split the text file, but am not able to store it in my list the way I would like. This is what I have so far for reading the file:[note..i removed the splitting portion as the code was getting too complex]
[code]
import java.io.*;
import java.util.Scanner;
import java.util.Locale;


public class InputWindow
{
static final String carFile = "Cars";
String[] product;
String[] model;
String[] manufacturer;
String[] typeCode;
String[] idNo;
int[] locCode;
int[] msrp;
int[] unitCost;
int[] discRate;
int[] stockQty;


public InputWindow()throws FileNotFoundException
{

try
{
String filename="C:\cars.txt";
BufferedReader input=new BufferedReader(new FileReader(filename));

int x=0;
String line=input.readLine();

while (line!=null)

{
System.out.println(line);
line=input.readLine();
}
input.close();
}
catch (IOException e)
{
System.out.println("Error reading from file");
}

}
public InputWindow(String s)throws FileNotFoundException
{

try
{
BufferedReader input=new BufferedReader(new FileReader(s));
int x=0;
String line=input.readLine();
while (line!=null)
{
System.out.println(line);
line=input.readLine();
}
input.close();
}
catch (IOException e)
{
System.out.println("Error reading from file");
}

}
}


[\code]

What do I do now in order to split the file and store it in the above array structures?
Was This Post Helpful? 0
  • +
  • -

#8 Java coder  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 26-March 08

Re: Help with file reading and data structures

Posted 29 March 2008 - 09:13 AM

[quote name='Java coder' date='28 Mar, 2008 - 02:34 PM' post='332680']

View Postspullen, on 27 Mar, 2008 - 01:48 PM, said:

I would definitely invest some time in looking at data structures other then arrays. I would either go with a linked list or something that can have an arbitrary depth, since you don't know how much data that you have in the text file. I would actually use a tree, http://java.sun.com/...ge-summary.html, the tree in the Java API actually keeps the data sorted (I believe).
good luck.


hi again! I have thought of using the string tokenizer class to separate the file tokens..but am getting the following error:

Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(Unknown Source)

What does this mean and how do I rectify it? The code is given below:

import java.io.*;
import java.util.*;

  class TokenTest 
  { 

	 public static void main (String[] args) 
	 {
		TokenTest tt = new TokenTest();
		tt.dbTest();
	 }
 

	 void dbTest() 
	 { 

		DataInputStream dis = null;
		String cars = null;
		String[] product=new String[10];;
		String[] model=new String[10];
		String[] manufacturer=new String[10];
		String[] typeCode=new String[10];
		String[] idNo=new String[10];
		int[] locCode=new int[10];
		int[] msrp=new int[10];
		int[] unitCost=new int[10];
		int[] discRate=new int[10];
		int[] stockQty=new int[10];

		try 
		{ 

		   File f = new File("C:\\cars.txt");
		   FileInputStream fis = new FileInputStream(f); 
		   BufferedInputStream bis = new BufferedInputStream(fis); 
		   dis = new DataInputStream(bis);

		   // read the first record of the database
		   while ( (cars = dis.readLine()) != null) 
		   {
			  int length=cars.length();
			  //StringTokenizer st = new StringTokenizer(inventory, "\\s*");
			  for(int i=0;i<=length;i++)
			  {
				  StringTokenizer st = new StringTokenizer(inventory, "\\s*");
				  product[i]=st.nextToken();
				  model[i]=st.nextToken();
				  manufacturer[i]=st.nextToken();
				  typeCode[i]=st.nextToken();
				  idNo[i]=st.nextToken();
				  locCode[i]=Integer.parseInt(st.nextToken());
				  msrp[i]=Integer.parseInt(st.nextToken());
				  unitCost[i]=Integer.parseInt(st.nextToken());
				  discRate[i]=Integer.parseInt(st.nextToken());
				  stockQty[i]=Integer.parseInt(st.nextToken());
			  }
		   }
			for(int i=0;i<=10;i++)
			{
				System.out.println(product[i]);
				System.out.println("\n");
				System.out.println(model[i]);
				System.out.println("\n");
				System.out.println(manufacturer[i]);
			}

		}
		catch (IOException e)
		{ 
		   // catch io errors from FileInputStream or readLine() 
		   System.out.println("Got an IOException error: " + e.getMessage()); 

		}
		finally 
		{ 
		   // if the file opened okay, make sure we close it 
		   if (dis != null) 
		   {
			  try 
			  {
				 dis.close();
			  }
			  catch (IOException ioe) 
			  {
				 System.out.println("IOException error trying to close the file: "); 
			  }

		   } // end if

		} // end finally

	 } // end dbTest

  } // end class 




Please tell me what I'm doing wrong, as I cannot proceed without this step. Thanks in advance! :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1