0
public static void outputFile() {
    HabitItem it;
    try {
        File path = new File("output.txt");
        FileOutputStream fout = new FileOutputStream(path);
        DataOutputStream dos = new DataOutputStream(fout);
        while (!stackHabitItems.isEmpty()) {
            it = stackHabitItems.pop();
            dos.writeChars("<\n");
            for(int i = 0; i < 7; i++) {
                if (it.isDayCompleted[i]) {
                    dos.writeInt(1);
                }
                else {
                    dos.writeInt(0);
                }
            }
            dos.writeChars("\n");

            dos.writeInt(it.id);

            dos.writeChars("\\>\n");
        }
        fout.close();
    }
    catch (Exception e) {
        System.out.println("Failed to open file output.txt");
    }
}

All I'm trying to do is write an array of booleans and an integer into a file enclosed by < />

My file might look like this (assuming one iteration) < 1 0 1 0 0 0 1 42 >

But the dos.writeInt is failing to produce normal output. Instead it displays <
> Where the blank spaces are filled by Squares

Why does my code not work? I feel like I'm using DataOutputStream correctly.

Cameron
  • 2,805
  • 3
  • 31
  • 45

2 Answers2

1

Try PrintStream or your FileOutputStreamdirectly instead and it will produce human readable results.

You could try like this (might still need separators between ints)

public static void outputFile() {
    File path = new File("output.txt");
    try (FileOutputStream fout = new FileOutputStream(path);
          PrintWriter dos = new PrintWriter(fout)) {
        while (!stackHabitItems.isEmpty()) {
            HabitItemit = stackHabitItems.pop();
            dos.println("<");
            for(int i = 0; i < 7; i++) {
                if (it.isDayCompleted[i]) {
                    dos.print(1);
                }
                else {
                    dos.print(0);
                }
            }
            dos.println();

            dos.print(it.id);

            dos.println("\\>");
        }
    } catch (Exception e) {
        System.out.println("Failed to open file output.txt");
    }
}
Jan
  • 13,738
  • 3
  • 30
  • 55
0

How can I make DataOutputStream write a bool or integer to txt file?

You can't. Booleans and integers are primitive data types. You can either write them as binary with DataOutputStream to a binary file, or write them as Strings to a text file with a Writer and constructions such as writer.write(""+bool).

user207421
  • 305,947
  • 44
  • 307
  • 483