reading text file into constructor array (java) - java

I have a textfile with some values.
textfile data
line1row1 line1row2 55
line2row1 line2row2 44
line3row1 line3row2 33
I have a data class where i have created a contructor. the data which goes into the array, i want read from the text file.
import java.io.*;
import java.util.*;
class Data{
public Data(String entry1, String entry2, int entry3){}
}
public class readData {
public static void main(String[] args) throws Exception{
BufferedReader inFile = new BufferedReader (new FileReader ("scores.txt"));
Data entrydata[] = new Data[3]; //create new constructor array
for(int i = 0; i < entrydata.length; i++ ){
entrydata[i] = inFile.readLine();
}
}
}
I get an error on "inFile.readLine()"... Cannot Convert from String to Data(where "Data" refers to class)
I can hardcode the data [as below] but want it to be read from the file instead
Data entrydata[] = new Data[3];
entrydata [0] = new Data("line1row1 ", "line1row2 ", 55);
entrydata [1] = new Data("line2row1 ", "line2row2 ", 44);
entrydata [2] = new Data("line3row1 ", "line3row2 ", 33);
The reason I want to do this, is so that I can access the informatin stored in the array.

inFile.readline() returns a string, which isn't a Data object and so you get the error message. You need to split the string you read from the file into an array and the use the array elements to create your data items. Something like:
String[] tmp = inFile.readline().split( " " );
entrydata[i] = new Data( tmp[0], tmp[1], Integer.parseInt( tmp[2] ) );

I woud do something like this
class Data{
String entry1, entry2;
int entry3;
public Data(String[] datas) throws NumberFormatException {
entry1 = datas[0];
entry2 = datas[1];
entry3 = Integer.parseInt(datas[2]);
}
}
.
.
.
.
Data entrydata[] = new Data[3]; //this is not a constructor
for(int i = 0; i < entrydata.length; i++ ){
entrydata[i] = new Data(inFile.readLine().split(" ")); //this is the constructor
}

How could the readLine method, which reads a line of text from the file, know how to transform the line into a Data instance? It doesn't read in your mind.
So you have to tell it how to transform the line into three components. You might use the String.split method to split the line at every space character, and the Integer.parseInt method to transform the third token into an integer.
Also, your code assumes that the file contains exactly 3 lines. If that's not necessarily the case, you should loop until the next line is null, and put each Data instance into a List<Data> rather than an array. The list will automatically grow in size, which an array can't do.

Your readData class does not have a constructor or a method. The code in line 11-15 needs to be in a method/constructor.
If the length each entry is fixed, you might try line.substring(...) instead of line.split(...).
The name of the class should be ReadData.

This code will definetly work:
FileReader fr =new FileReader("src/FilePractice.txt");
BufferedReader in =new BufferedReader(fr);
String line;
while((line = in.readLine()) != null){
String[] arrray=line.split(",");
RelationShip r=RelationShip.valueOf(arrray[2]);
new Data(arrray[0],arrray[1],r,Integer.parseInt(arrray[3]));
System.out.println(arrray[0]+arrray[1]+arrray[2]+arrray[3]);

Related

How can I read from a CSV file into 2 ArrayLists depending on the data type I have got in the File?

I'm a beginner in java and I have no clue how to read from a CSV file into 2 ArrayLists maybe using tokens and. Type. (list->Array)
Depending on the token we add to one list or another.
Update: The format of the file is fixed. This is the format:
Andrew,Nick,11,Pen,Apple,Backpack,5500.0,570.0,4700.0
Ex:
Name,Description,55.0,100.0
Name into an ArrayList of String.
55.0 into an ArrayList of Double;
This is my code,im trying to figure out the basic first of all.
public class CSVRead {
public static void main(String[] arg) throws Exception {
BufferedReader CSVFile = new BufferedReader(new FileReader("Auto2.csv"));
String data= CSVFile.readLine();
while (data != null){
String[] dataArray = data.split(",");
for (String item:dataArray) {
System.out.print(item + "\t");
}
System.out.println();
data = CSVFile.readLine();
}
CSVFile.close();
System.out.println();
}
}
You can try the following code. As an example I have taken index zero as the name field and the index six as the double value you need. According to the format you can get the actual field index and add it in to your lists.
public void loadData() throws IOException {
List<String> namesList = new ArrayList<>();
List<Double> someDoubleList = new ArrayList<>();
BufferedReader CSVFile = new BufferedReader(new FileReader("/Users/leon/Desktop/Auto2.csv"));
String data = CSVFile.readLine();
while (data != null) {
String[] dataArray = data.split(",");
// Add the names to string list as the index of it is zero
namesList.add(dataArray[0]);
// Add the double value to double list as the index of it is six.
someDoubleList.add(Double.parseDouble(dataArray[6]));
data = CSVFile.readLine();
}
CSVFile.close();
}

JAVA - How to create an array of objects?

I need to read a CSV file into an array of Objects.
I didn't realise that it had to go into one, and just made an ArrayList instead. I now need to fix that, and have no idea what I'm doing.
This is my code to read the CSV file into a multidimensional array.
public static void readClub() throws IOException {
BufferedReader clubBR = new BufferedReader(new FileReader(new File("nrlclubs.txt")));
String line = "";
ArrayList<String[]> clubsArr = new ArrayList<String[]>();
while ((line = clubBR.readLine()) != null) {
String[] club = new String[3];
for (int i = 0; i < 3; i++) {
String[] value = line.split(",", 3);
club[i] = value[i];
}
clubsArr.add(club);
}
A snippet of my CSV file is this:
Glebe,G Shield,Glebe District
Cumberland,C Shield,Central Cumberland
Annandale,A Shield,Annandale District
University,Lion,Sydney Uni Rugby League Club
Souths,Rabbit,South Sydney,Rabbitohs
Easts,Rooster,Eastern Suburbs,Roosters,Sydney Roosters
Balmain,Tiger,Tigers,Balmain Tigers
Newtown,Jets,Jets,Newtown Jets,Bluebags
The first word is the Team name, the second word is the Team mascot, and the rest are the alias's.
Now the question is, how do i do the same thing, but with an Array of Objects (in a class called Clubs)?
I just spent a few hours trying to get this working, only to be told its wrong, and the Array of Objects is doing my head in :'(
Thanks heaps!
edit:
ok, the actual question is this:
the program should read the content of the data file (NRLclubs.txt) into memory into an appropriate array of objects (see previous page for descriptions of the class). Do not assume that the file exists.
The description of the class is this:
Club class: the Club class represents an individual NRL club within the competition. The Club class needs to store data for the current club name, current club mascot, any aliases by which the club is or has been known. As well as the normal methods that should be created for a class (eg, constructors, ‘setters’, and ‘getters’) you will need to decide upon appropriate methods for this class based upon the general requirements of the assignment specification.
Create a new Class that will hold the data of a row.
In the easiest case you could create a class like this:
class MyClass {
public String column1;
public String column2;
public ArrayList<String> aliases = new ArrayList<String>();
public void addAliases(String[] a){
for(int i=2;i<a.length;i++){
aliases.add(a[i]);
}
}
}
Then change your ArrayList like so: ArrayList<MyClass> clubsArr = new ArrayList<MyClass>();
and your reading part like so:
while ((line = clubBR.readLine()) != null) {
MyClass club = new MyClass;
String[] value = line.split(",", 3);
club.column1 = value[0];
club.column2 = value[1];
// etc...
clubsArr.add(club);
}
MyClass[] clubs = clubsArr.toArray();
That way you will later be able to get a value from one of the objects by using its attributename (in this case for example .column2) instead of some index you would have to keep in mind.
Note that you can call the attributes in the class to your liking (e.g. clubname instead of column1)
EDIT (to help with OPs edit)
To check, if the file exists, replace the line
BufferedReader clubBR = new BufferedReader(new FileReader(new File("nrlclubs.txt")));
with
File file = new File("nrlclubs.txt");
if(!file.exists()){
System.exit(1); // no use to go any further if we have no input
}
BufferedReader clubBR = new BufferedReader(new FileReader(file));
I don't understand your question well but maybe you are looking for this:
public static void readClub() throws IOException {
BufferedReader clubBR = new BufferedReader(new FileReader(new File("nrlclubs.txt")));
String line = "";
ArrayList<Clubs> clubs = new ArrayList<Clubs>();
while ((line = clubBR.readLine()) != null) {
Clubs club = new Clubs();
String[] value = line.split(",", 3);
club.name = value[0];
club.mascot = value[1];
club.alias = value[2];
clubs.add(club);
}
}

I want to read a text file, split it, and store the results in an array

I have a text file which has 10 fields(columns)each separated by a tab.And i have several such rows.I wish to read the text file, split it for every column, using a "tab" delimiter and then storing it in an array of 10 columns and unlimited rows.Can that be done?
An array can't have "unlimited rows" - you have to specify the number of elements on construction. You might want to use a List of some description instead, e.g. an ArrayList.
As for the reading and parsing, I'd suggest using Guava, particularly:
Files.newReaderSupplier
CharStreams.readLines
Splitter
(That lets you split the lines as you go... alternatively you could use Files.readLines to get a List<String>, and then process that list separately, again using Splitter.)
BufferedReader buf = new BufferedReader(new FileReader(fileName));
String line = null;
List<String[]> rows = new ArrayList<String[]>();
while((line=buf.readLine())!=null) {
String[] row = line.split("\t");
rows.add(row);
}
System.out.println(rows.toString()); // rows is a List
// use rows.toArray(...) to convert to array if necessary
Here is a simple way to load a .txt file and store it into a array for a set amount of lines.
import java.io.*;
public class TestPrograms {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String conent = new String("da");
String[] daf = new String[5];//the intiger is the number of lines +1 to
// account for the empty line.
try{
String fileName = "Filepath you have to the file";
File file2 = new File(fileName);
FileInputStream fstream = new FileInputStream(file2);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
int i = 1;
while((conent = br.readLine()) != null) {
daf[i] = conent;
i++;
}br.close();
System.out.println(daf[1]);
System.out.println(daf[2]);
System.out.println(daf[3]);
System.out.println(daf[4]);
}catch(IOException ioe){
System.out.print(ioe);
}
}
}

Read input as array

I want to make something read from inputstream to store in an int[] when I type "read 1 2 3 4". what should i do?
I do not know the size of the array, everything is dynamic...
Here is the current code:
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
String line = stdin.readLine();
StringTokenizer st = new StringTokenizer(line);
String command = st.nextToken();
if (command.equals("read")) {
while (st.nextToken() != null) {
//my problem is no sure the array size
}
}
You need to build something to parse the input stream. Assuming it's literally as uncomplex as you've indicated the first thing you need to do is get the line out of the InputStream, you can do that like this:
// InputStream in = ...;
// read and accrue characters until the linebreak
StringBuilder sb = new StringBuilder();
int c;
while((c = in.read()) != -1 && c != '\n'){
sb.append(c);
}
String line = sb.toString();
Or you can use a BufferedReader (as suggested by comments):
BufferedReader rdr = new BufferedReader(new InputStreamReader(in));
String line = rdr.readLine();
Once you have a line to process you need to split it into pieces, then process the pieces into the desired array:
// now process the whole input
String[] parts = line.split("\\s");
// only if the direction is to read the input
if("read".equals(parts[0])){
// create an array to hold the ints
// note that we dynamically size the array based on the
// the length of `parts`, which contains an array of the form
// ["read", "1", "2", "3", ...], so it has size 1 more than required
// to hold the integers, thus, we create a new array of
// same size as `parts`, less 1.
int[] inputInts = new int[parts.length-1];
// iterate through the string pieces we have
for(int i = 1; i < parts.length; i++){
// and convert them to integers.
inputInts[i-1] = Integer.parseInt(parts[i]);
}
}
I'm sure some of these methods can throw exceptions (at least read and parseInt do), I'll leave handling those as an exercise.
You either use a storing structure with nodes, that you can easily append one after another, or, if you really must use arrays, you need to allocate space periodically, as it becomes necessary.
Parse-out the data and keyword from your string then push it into something like this:
public static Integer[] StringToIntVec( String aValue )
{
ArrayList<Integer> aTransit = new ArrayList<Integer>();
for ( String aString : aValue.split( "\\ ") )
{
aTransit.add( Integer.parseInt( aString ) );
}
return aTransit.toArray( new Integer[ 0 ] );
}

Java : Resizing a multidimensional array

I have a multidimensional array built from Strings that is initially created with the size [50][50], this is too big and now the array is full of null values, I am currently trying to remove these said null values, I have managed to resize the array to [requiredSize][50] but cannot shrink it any further, could anyone help me with this? I have scoured the internet for such an answer but cannot find it.
Here is my complete code too (I realise there may be some very unclean parts in my code, I am yet to clean anything up)
import java.io.*;
import java.util.*;
public class FooBar
{
public static String[][] loadCSV()
{
FileInputStream inStream;
InputStreamReader inFile;
BufferedReader br;
String line;
int lineNum, tokNum, ii, jj;
String [][] CSV, TempArray, TempArray2;
lineNum = tokNum = ii = jj = 0;
TempArray = new String[50][50];
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the file path of the CSV");
String fileName = in.readLine();
inStream = new FileInputStream(fileName);
inFile = new InputStreamReader(inStream);
br = new BufferedReader(inFile);
StringTokenizer tok,tok2;
lineNum = 0;
line = br.readLine();
tokNum = 0;
tok = new StringTokenizer(line, ",");
while( tok.hasMoreTokens())
{
TempArray[tokNum][0] = tok.nextToken();
tokNum++;
}
tokNum = 0;
lineNum++;
while( line != null)
{
line = br.readLine();
if (line != null)
{
tokNum = 0;
tok2 = new StringTokenizer(line, ",");
while(tok2.hasMoreTokens())
{
TempArray[tokNum][lineNum] = tok2.nextToken();
tokNum++;
}
}
lineNum++;
}
}
catch(IOException e)
{
System.out.println("Error file may not be accessible, check the path and try again");
}
CSV = new String[tokNum][50];
for (ii=0; ii<tokNum-1 ;ii++)
{
System.arraycopy(TempArray[ii],0,CSV[ii],0,TempArray[ii].length);
}
return CSV;
}
public static void main (String args[])
{
String [][] CSV;
CSV = loadCSV();
System.out.println(Arrays.deepToString(CSV));
}
}
The CSV file looks as follows
Height,Weight,Age,TER,Salary
163.9,46.8,37,72.6,53010.68
191.3,91.4,32,92.2,66068.51
166.5,51.1,27,77.6,42724.34
156.3,55.7,21,81.1,50531.91
It can take any size obviously but this is just a sample file.
I just need to resize the array so that it will not contain any null values.
I also understand a list would be a better option here but it is not possible due to outside constraints. It can only be an multi dimensional array.
I think you need 3 changes to your program
After your while loop lineNum will be 1 more than the number of lines in the file so instead of declaring CSV to String[tokNum][50] declare it as CSV = new String[tokNum][lineNum-1];
tokNum will be the number of fields in a row so your for loop condition should be ii<tokNum rather than ii<tokNum-1
The last parameter for your arraycopy should be lineNum-1
i.e. the modified code to build your CSV array is:
CSV = new String[tokNum][lineNum-1];
for (ii=0; ii<tokNum ;ii++)
{
System.arraycopy(TempArray[ii],0,CSV[ii],0,lineNum-1);
}
and the output will then be:
[[Height, 163.9, 191.3, 166.5, 156.3], [Weight, 46.8, 91.4, 51.1, 55.7],
[Age, 37, 32, 27, 21], [TER, 72.6, 92.2, 77.6, 81.1],
[Salary, 53010.68, 66068.51, 42724.34, 50531.91]]
Notice that you don't really need to handle the first line of the file separately from the others but that is something you can cover as part of your cleanup.
10 to 1 this is a homework assignment. However, it looks like you've put somethought into it.
Don't make the TempArray variable. Make a "List of List of Strings". Something like:
List<List<String>> rows = new ArrayList<ArrayList<String>>();
while(file.hasMoreRows()) { //not valid syntax...but you get the jist
String rowIText = file.nextRow(); //not valid syntax...but you get the jist
List<String> rowI = new ArrayList<String>();
//parse rowIText to build rowI --> this is your homework
rows.add(rowI);
}
//now build String[][] using fully constructed rows variable
Here's an observation and a suggestion.
Observation: Working with (multidimensional) arrays is difficult in Java.
Suggestion: Don't use arrays to represent complex data types in Java.
Create classes for your data. Create a List of people:
class Person {
String height; //should eventually be changed to a double probably
String weight; // "
//...
public Person( String height, String weight /*, ... */ ) {
this.height = height;
this.weight = weight;
//...
}
}
List<Person> people = new ArrayList<Person>();
String line;
while ( (line = reader.nextLine()) != null ) {
String[] records = line.split(",");
people.add(new Person (records[0], records[1] /*, ... */));
}

Categories

Resources