shishi
shishi

Reputation: 63

How to create item objects from reading a text file?

I'm trying to read data from a text file and create Item Objects with it. Item Objects have fields String title, String formatt, boolean onLoan, String loanedTo and String dateLoaned. In my save()method, I print every object to a text file in a new line and the fields are seperated by "$" (dollar sign). How can I read the text file line by line and create a new object from each line and add it to an array.

TextFile Example:

StarWars$DVD$false$null$null

Aliens$Bluray$true$John$Monday

public void save() {
    String[] array2 = listForSave();
    PrintWriter printer = null;

      try {
          printer = new PrintWriter(file);

            for (String o : array2) {
            printer.println(o);
            }
            printer.close();
        } catch ( IOException e ) {
            e.printStackTrace();
        }

}
public void open(){
    try{

    FileReader fileReader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    StringBuffer stringBuffer = new StringBuffer();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        stringBuffer.append(line);
        stringBuffer.append("\n");
    }
    fileReader.close();
    System.out.println("Contents of file:");
    System.out.println(stringBuffer.toString());

    }catch ( IOException e ) {
        e.printStackTrace();
    }


}

Thanks everyone. Here's my final code:

public void open(){
    try{

    FileReader fileReader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    String line;
    String[] strings;
    while ((line = bufferedReader.readLine()) != null) {
        strings = line.split("\\$");
        String title = strings[0];
         String format = strings[1];
         boolean onLoan = Boolean.parseBoolean(strings[2]);
         String loanedTo = strings[3];
         String dateLoaned = strings[4];

         MediaItem superItem = new MediaItem(title,format, onLoan,loanedTo,dateLoaned);
         items.add(superItem);

    }
    fileReader.close();


    }catch ( IOException e ) {
        e.printStackTrace();
    }


}

Upvotes: 4

Views: 2599

Answers (3)

NaN
NaN

Reputation: 8611

You could try this to "parse" every line of your file

String[] result = "StarWars$DVD$false$null$null".split("\\$");
for (int i=0; i<result.length; i++) {
     String field = result[i]
     ... put the strings in your object ...  
}

Upvotes: 0

Robb
Robb

Reputation: 2686

quick and dirty solution might be...

public void open(){
    try{
    ArrayList<Item> list = new ArrayList<Item>(); //Array of your ItemObject

    FileReader fileReader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    StringBuffer stringBuffer = new StringBuffer();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
      Item itm = new Item(); //New Item Object 
      String [] splitLine = line.split("\\$");

      item.title = splitLine[0];
      item.format = splitLine[1];
      item.onLoan = Boolean.parseBoolean(splitLine[2]);
      item.loanedTo = splitLine[3];
      item.dateLoaned = splitLine[4];

      list.add(itm);

      stringBuffer.append(line);
      stringBuffer.append("\n");
    }
    fileReader.close();
    System.out.println("Contents of file:");
    System.out.println(stringBuffer.toString());

    }catch ( IOException e ) {
        e.printStackTrace();
    }
}

But this is won't scale if you need to re-arrange or add new fields.

Upvotes: 0

fabian
fabian

Reputation: 82461

String line = // input line e.g. "Aliens$Bluray$true$John$Monday"
String[] strings = line.split("\\$"); // use regex matching "$" to split
String title = strings[0];
String formatt = strings[1];
boolean onLoan = Boolean.parseBoolean(strings[2]);
String loanedTo = strings[3];
String dateLoaned = strings[4];
// TODO: create object from those values

Maybe you need to handle null differently (in case you want the String "null" to be converted to null); note that you can't distinguish if null or "null" was saved.

This function converts "null" to null and returns the same string otherwise:

String convert(String s) {
    return s.equals("null") ? null : s;
}

Reading the objects to an array

Since you don't know the number of elements before reading all lines, you have to work around that:

  1. Write the number of objects in the file as first line, which would allow you to create the array before reading the first object. (Use Integer.parseInt(String) to convert the first line to int):

    public void save() {
        String[] array2 = listForSave();
        PrintWriter printer = null;
    
          try {
              printer = new PrintWriter(file);
              printer.println(array2.length);
                for (String o : array2) {
                    printer.println(o);
                }
                printer.close();
            } catch ( IOException e ) {
                e.printStackTrace();
            }
    
    }
    public void open(){
        try{
    
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        StringBuffer stringBuffer = new StringBuffer();
        int arraySize = Integer.parseInt(stringBuffer.readLine());
        Object[] array = new Object[arraySize];
        int index = 0;
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            // split line and create Object (see above)
            Object o = // ...
            array[index++] = o;
        }
        //...
        }catch ( IOException e ) {
            e.printStackTrace();
        }
        //...
    }
    

    or

  2. Use a Collection, e.g. ArrayList to store the objects and use List.toArray(T[]) to get an array.

Upvotes: 1

Related Questions