简体   繁体   中英

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

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.

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

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

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");
    }
}

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM