How do I create object objects when reading a text file?

I am trying to read data from a text file and create Item objects with it. Element Objects have fields Line Header, String formatt, boolean onLoan, String loanedTo, and String dateLoaned. In my save () method, I print each object to a text file on a new line, and the fields are separated by a "$" (dollar sign) character. How can I read a text file line by line and create a new object from each line and add it to the array.

Example TextFile:

StarWars $ DVD $ False $ null $ null

Strangers $ 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();
    }


}

      

+3


source to share


3 answers


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 it null

differently (in case the String "null"

needs to be converted to null

); please note that you cannot tell if null

or was saved "null"

.

This function converts "null"

to null

and returns the same string otherwise:

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

      



Reading objects into an array

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

  • Enter the number of objects in the file as the first line, which will allow you to create an array before reading the first object. (Use Integer.parseInt(String)

    to convert first string 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

  • Use Collection

    for example. ArrayList

    to store objects and use List.toArray(T[])

    to get an array.
+1


source


You can try this to parse each 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 ...  
}

      

0


source


a quick and dirty solution can 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 it won't scale if you need to reorder or add new fields.

0


source







All Articles