how to store the data read from the txt file, and store it into different array?

for example,

name,age,address

i know how to read them differently, but don know how to store it... :cry:

FileReader fr = new FileReader("abc.txt");


input = new BufferedReader(fr);
line = input.readLine();


while (line != null)
{
StringTokenizer tokens =
new StringTokenizer(line, ", \t");
String token;


while(tokens.hasMoreTokens())
{
token = tokens.nextToken();
System.out.println(token); /* trying to see what is the output, but donno how to store it to different array*/
}
line = input.readLine();


}
input.close();
}

Dani AI

Generated

Good progress in this thread — was right to model each row as an object, and 's suggestion to "accumulate" reads into a single structure is exactly the next step. Rather than a fixed-size array, use a growable collection (ArrayList) or store raw tokens first (String[]) and convert to objects once parsing succeeds. That avoids sizing problems and makes later lookups and filtering straightforward.

A minimal, modern pattern (different from the examples already posted) is to read lines into a list of token arrays, trimming and validating each row as you go:

List<String[]> rows = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader("abc.txt"))) {
    String header = br.readLine(); // optional
    String line;
    while ((line = br.readLine()) != null) {
        String[] cols = line.split(",", -1);
        for (int i = 0; i < cols.length; i++) cols[i] = cols[i].trim();
        if (cols.length >= 3) rows.add(cols); // validate length before using
    }
}

Troubleshooting notes pulled from the thread: the "non‑static variable this cannot be referenced from a static context" error comes from trying to instantiate a non‑static inner class from static main — fix by moving the class to top level or making it static. The "cannot resolve symbol" you saw often happens when a local/inner class is declared after it's used or when braces are mismatched. Also watch for stray semicolons after if(...) which make the if empty and will let you call nextToken() when none exists.

Extras: prefer String.split or a dedicated CSV parser (OpenCSV/Apache Commons CSV) if fields can contain commas or quotes; always trim() tokens and guard Integer.parseInt with try/catch for NumberFormatException; use Map<String,YourObject> if you need fast lookup by a key (name). Add clear getters and toString() on your record class to simplify debugging.

Recommended Answers

All 10 Replies

Think about this situation as similar to keeping running totals. Create another variable that will store the complete file. After each read, append the read in data to the variable.

Next time, put your code in the code block.

how to append the read in data to the variable? :sad:

that is what i donno, i've tried looking for it, but its in C...

Each row contains a persons info. The best thing to do is create a class that holds each row. Here is an example:

class PersonInfo
{
	private String name;
	private int age;
	private String address;

	public PersonInfo(String name, int age, String address)
	{
		this.name=name;
		this.age=age;
		this.address=address;
	}
}

Then in your loop above you should write:

//create array outside
PersonInfo[] listOfInfo = new PersonInfo[100];	//change 100 to the desired size!

//maintain # of items in array
int listOfInfoSize=0;

//read lines
while (line != null) 
{
	StringTokenizer tokens = new StringTokenizer(line, ", \t");

	//get three tokens
	String nameToken = tokens.nextToken();
	String ageToken = tokens.nextToken();
	String addressToken = tokens.nextToken();

	//create personinfo object
	PersonInfo obj = new PersonInfo(nameToken, ageToken, addressToken);

	//add to array
	listOfInfo[listOfInfoSize++]=obj;
}

As you see above, the array will hold all the PersonInfo objects. Each PersonInfo object represents a row in the text file. You should add getter methods to the PersonInfo class. Then you can use this array to get any info you need.

For more help,

:!: got some idea now... will try this afternoon... :cheesy:

thanks! :D

//create array outside
PersonInfo[] listOfInfo = new PersonInfo[100];	//change 100 to the desired size!

//maintain # of items in array
int listOfInfoSize=0;

//read lines
while (line != null) 
{
	StringTokenizer tokens = new StringTokenizer(line, ", \t");

	//get three tokens
	String nameToken = tokens.nextToken();
	String ageToken = tokens.nextToken();
	String addressToken = tokens.nextToken();

	//create personinfo object
	PersonInfo obj = new PersonInfo(nameToken, ageToken, addressToken);

	//add to array
	listOfInfo[listOfInfoSize++]=obj;
}

the object cannot be created. it says that "non-static variable this cannot be referenced from a static context"

Which line did it have a problem with?

PersonInfo obj = new PersonInfo(nameToken, ageToken, addressToken);

;)

Are you creating the PersonInfo class definition in the same file as the rest of your program? If you are, you need to define the PersonInfo class as static.

public static void main(String[] args) 
	{
	Item[] abc= new Item[10];
	String line;
	int size=0;
	
	BufferedReader readResults = new BufferedReader(new FileReader("abc.txt"));
	line = readResults.readLine();
	
	while (line!=null)
	{
	
	StringTokenizer tokens = new StringTokenizer(line, ",");
		
	while (tokens.hasMoreTokens()) 
	{
	
	String nameToken = tokens.nextToken();
	int markaToken = Integer.parseInt(tokens.nextToken());
	int markbToken = Integer.parseInt(tokens.nextToken());

	abc[size] = new Item(nameToken, markaToken, markbToken);
	size++;

	}
	}

class Item
{
	private String name;
	private int marka, markb;

	public Item(String name, int marka, int markb)
	{
		this.name=name;
		this.marka=marka;
		this.markb=markb;
	}
}

got another error "cannot resolve symbol"

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

public class test 
{
	public static void main(String[] args) 
	{
		Item[] abc= new Item[10];
		String line, subjectName;
		int size=0;
	
		try
		{
		BufferedReader readResults = new BufferedReader(new FileReader("abc.txt"));
	
		subjectName = readResults.readLine();
		line = readResults.readLine();
		
		while (line!=null)
		{
	
		
			StringTokenizer tokens = new StringTokenizer(line, ",",false);
			String nameToken = tokens.nextToken();
			if((tokens.hasMoreTokens()) );
			int markaToken = Integer.parseInt(tokens.nextToken());
			int markbToken = Integer.parseInt(tokens.nextToken());

			abc[size] = new Item(nameToken, markaToken, markbToken);
			size++;
			line = readResults.readLine();
		
		}
		System.out.println(subjectName);  /* this 4 lines is to check whether the infomation have been stored*/
		System.out.println(abc[0].getname());
			System.out.println(abc[1].getmarka());
				System.out.println(abc[2].getmarkb());
				
		}
		
	
		catch(FileNotFoundException e)
		{}
	
		catch(IOException e)
		{}
	}
	
}

class Item
{
	private String name;
	private int marka, markb;

	public Item(String name, int marka, int markb)
	{
		this.name=name;
		this.marka=marka;
		this.markb=markb;
	}
	public double getmarka()
	{
		return marka;
	}
	
	public double getmarkb()
	{
		return markb;
	}
	
	public String getname()
	{
		return name;
	}
	
}

i finally got it correct... thanks to those look at the thread and help me! :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.