Search code examples
javaiofileoutputstreamfilewriterobjectoutputstream

How to write a point object to a text file


I'm trying to write a list that contains a list of points in to a text file.I've managed to write the method to save a a point to text file. However, I'm getting some extra characters in the output

try {
    FileOutputStream fileOut = new FileOutputStream(path);
    ObjectOutputStream out = new ObjectOutputStream(fileOut);

    for(int i = 0; i < pointList.size(); i++){
        String s = parseString( pointList.get(i));

        out.writeObject(s);
    }

    out.close();
    fileOut.close();
} catch (IOException i) {
    i.printStackTrace();
}

private static String parseString(Point P){
    String point = String.valueOf(P.getX()) + "," + String.valueOf(P.getY()) ;
    System.out.println("String: " +point);
    return point;
}

This is the point list

List<Point> pointList = new ArrayList();
pointList.add(new Point(100,200));
pointList.add(new Point(300,500));
pointList.add(new Point(400,200));
pointList.add(new Point(100,500));
pointList.add(new Point(400,200![enter image description here][1]));

This is the output of the write method https://i.sstatic.net/hqMDK.png

I don't seem to understand how to get rid of the characters on the first line of the output and the t on each line

Thanks for you help


Solution

  • ObjectOutputStream writes binary serialization data to the stream. It's not supposed to produce human-readable output.

    If you want to write something human-readable, then use something like PrintWriter instead.