Creating an array of Objects from reading a .txt file and saving line by line into object array

烈酒焚心 提交于 2021-02-11 15:44:43

问题


The project prompt looks like this: In Netbeans create a project named Project1, be sure to create a package, DO NOT use the default package. There will be two java files, the first most likely named Project1.java (which contains main) and the second named Record.java which contains a variable containing ONE LINE OF DATA (or record) read from the file. In your main class (not in Record.java) create an array of Record objects. When the program starts have main() call a method that reads each line of text from the file, creates a Record object containing that line and places the object in the next available slot of the array.

The text file I have saved is this:

John, Doe, jd@yahoo.com, 123456, green, 19.24
Mary, Jane, maryj@gmail.com, 7654321, blue, 27.54
Curly, Howard, nyuknyuk@msn.com, 888765, purple, 0.0
Bart, Simpson, donthaveacow@hotmail.com, 457673, magenta, 432.23
Clark, Kent, superdude@dailyplanet.com, 976834, red, 11.10

My Issue is not understanding how to read from the text file line by line and storing it in an array of Objects Record. I can create an array of Strings easily but it does not really help the situation. I am not sure if I am making it more complicated then it has to be or if I am completely wrong. SO far this is my code

project1:
import java.io.*;
import java.util.Scanner;
public class Project1 {
protected static int arrayLength=5 ;
protected static String filename ="data.txt";

   public static void main(String[] args)throws Exception{
     Record [] objects = new Record[arrayLength];
     ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
     Record obj = (Record) in.readObject();
     System.out.print(obj.getRecord());
   }

   public static void arrayObjects()throws IOException, ClassNotFoundException{
     Record [] objects = new Record[arrayLength];
     ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
     Record obj = (Record) in.readObject();



      }
       }
package Project1;

import java.io.*;
import java.util.Scanner;
import java.nio.file.*;; 



    /**
     *
     * @author lexif
     */
    public class Record{
     private String path;
     private String data;
     private int number =1;
    public Record(String file_path) throws IOException{
        path = file_path;

      }
    public String getRecord() throws FileNotFoundException, IOException{
        FileReader open = new FileReader(path); 
        BufferedReader reader = new BufferedReader(open);
        String data1 = reader.readLine();
        return data1;
    }

    public String OpenFile(String filename,int num) throws IOException {
        FileReader fr = new FileReader (filename);
        BufferedReader textreader = new BufferedReader(fr);
        for (int i=0; i < num; i++) {
        data = textreader.readLine();
        }
        textreader.close();
        return data;
        }

     public int readLines () throws IOException{
           FileReader file_to_read = new FileReader(path);
           BufferedReader br = new BufferedReader(file_to_read);

           String aline;
           int numLines=0;

           while((aline = br.readLine()) != null){
               numLines++;
           }
           br.close();
           return numLines;
       }
    }

回答1:


Please use this code

   public Record[] readRecord(String pathFile) throws IOException {
        List<String> list = Files.readAllLines(Paths.get(pathFile));
        Record[] records = new Record[list.size()];
        for(int i = 0; i< list.size(); i++) {
            records[i] = new Record(list.get(i));
        }
        return records;
    }



回答2:


First of all you should have the readLines() function in the Project class. Then What all you have to do is you need to modify your readLines() function to create the RecordObject and return the List of RecordObjects. Something like this

public List<Record> readLines () throws IOException{
    FileReader file_to_read = new FileReader(path);
    BufferedReader br = new BufferedReader(file_to_read);

    String aline;
    int numLines=0;
    List<Record> recordList = new ArrayList<Record>();
    while((aline = br.readLine()) != null){

        Record rec = new Record(); // You can have a constructor which takes string as parameter also
        rec.setData(aline);
        recordList.add(rec);
        numLines++;
    }
    br.close();
    return recordList;
}

You don't need the OpenFile function in your record class and the getRecord should return only the 'data' member



来源:https://stackoverflow.com/questions/54779172/creating-an-array-of-objects-from-reading-a-txt-file-and-saving-line-by-line-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!