Search code examples
javafilebufferedreaderfilereaderprintwriter

Write Object to File "Persons.obj"


Hi there fellow Stackoverflowers. I had a question concerning Java, I'm supposed to put all the Objects p1 - p4 in a file called "personen.obj" and for p1, write all data to "persoon1.obj" etc.

Here's the code i'm working with, it doesn't include the Computer class because I thought that isn't neccessary.

This includes some Strings in Dutch, but every Person has a toString with their data. What's supposed to happen is that all the toStrings are written in those files.

import java.util.Calendar;

public class Main {
public static void main(String[] args) {
    int huidigJaar = Calendar.getInstance().get(Calendar.YEAR);
    int aanschafJaarC1 = huidigJaar - 4; // c1 is 4 jaar oud
    int aanschafJaarC2 = huidigJaar - 3; // c2 is 3 jaar oud
    Persoon p1 = new Persoon("Eric", 20000);
    Persoon p2 = new Persoon("Hans", 60000);
    Persoon p3 = new Persoon("Willem-Alexander", 8500000);
    Computer c1 = new Computer("Medion", 2000, aanschafJaarC1, "Super");
    Computer c2 = new Computer("Dell", 1500, aanschafJaarC2, "Home");
    if (p1.koop(c1)) {
        System.out.println("Deze koper bezit nu nog " + p1.getBudget());
    }
    if (p1.koop(c1)) {
        System.out.println("Deze koper bezit nu nog " + p1.getBudget());
    }
    if (p2.koop(c1)) {
        System.out.println("Deze koper bezit nu nog " + p2.getBudget());
    }
    if (p2.koop(c2)) {
        System.out.println("Deze koper bezit nu nog " + p2.getBudget());
    }
    if (p3.koop(new Computer("Dell", 1500, aanschafJaarC2, "Home"))) {
        System.out.println("Deze koper bezit nu nog " + p3.getBudget());
    }
    if (p3.koop(c2)) {
        System.out.println("Deze koper bezit nu nog " + p3.getBudget());
    }
    System.out.println("\n" + p1);
    System.out.println(p2);
    System.out.println(p3);
    if (p1.verkoop(c1, p3)) {
        System.out.println("Deze verkoper bezit nu nog " + p1.getBudget());
    }
    if (p2.verkoop(c1, p3)) {
        System.out.println("Deze verkoper bezit nu nog " + p2.getBudget());
    }
    if (p2.verkoop(c2, p1)) {
        System.out.println("Deze verkoper bezit nu nog " + p2.getBudget());
    }
    System.out.println("\n" + p1);
    System.out.println(p2);
    System.out.println(p3);
}
}

Solution

  • For simply writing a small number of strings to a file, I'd recommend using the class "PrintWriter". It wraps itself around a standard Writer and allows you to write any primitive data type and some Objects to a given "Writer" (In our case a FileWriter).

    This isn't the only way to write to a file of course nor is it the best way.

    I've quickly written up some code from memory, I haven't tested it but I'm pretty sure it works.

    /**
     * This method will write an array of strings to the given file.
     * If the append flag is set to true, the new data will be added to the end of the file.
     * 
     * Note:
     *  This is not only nor the best way to write to a file.
     * 
     * @param filename - The path to the file you want to write to.
     * @param data - The Strings you want to write to the file.
     * @param append - Should the new data be added to the end of the file?
     * @return If the write operation succeeded.
     */
    public static boolean writeStringsToFile(String filename, String[] data, boolean append) {
        boolean resultFlag = true;
    
        // The file class represents a file on a disk and provides some useful methods
        File file = new File(filename);
        //PrintWriter is used to write various data types to a given writer.
        PrintWriter printWriter = null;
    
        try {
            //This method will create an empty file, if there's not already one.
            //Will throw an IOException if it experiences an error creating the file.
            file.createNewFile();
    
            //A PrintWriter needs some kind of writer to output to, we'll use a FileWriter.
            //FileWriter is used for writing to files.
            //Will throw an IOException if the file doesn't exist (It should exist though)
            printWriter = new PrintWriter(new FileWriter(file, append));
    
            for(int i = 0; i < data.length; i++) {
                //Write the strings to the file, each on a new line.
                printWriter.println(data[i]);
            }
    
        } catch (IOException e) {
            //Uh oh. There was an error writing to the disk!
            e.printStackTrace();
    
            //We couldn't write to the disk, make sure we return false to let the caller know.
            resultFlag = false;
        } finally {
            //First check that we managed to create a PrintWriter before we try to close it.
            if (printWriter!=null)
                printWriter.close(); //Release the file from use.
        }
    
        return resultFlag;
    }
    

    It's also worth being aware of encodings. Certain systems can/will write text files in different ways than others, in most small cases it's not an issue but it could be potentially.

    I very highly recommend giving some of the oracle tutorials a read:

    Also make sure to give some other sites a read as most will give a different method to solve the same problem, albeit with different pros and cons.