Search code examples
javadataoutputstreamnxtlejos-nxj

LeJOS: How write integer data succesfully to a file in NXT


I am working on some AI project which I am supposed to implement a controller using fuzzy logic on my NXT. In order to evaluate properly my control strategy, I have the need to track the information measured by the color sensor and the data that are being send to the motors. For this, I was trying to implement a simple code to write some similar infos to a .txt file. Here is what I've accomplished so far:

import java.io.*;
import lejos.nxt.*;

public class DataLogger {

    public static void main(String[] args) {

        int count = 0;
        FileOutputStream fileStream = null;
        try {
            fileStream = new FileOutputStream(new File("Test.txt"));
        } catch (Exception e) {
            LCD.drawString("Can't make a file", 0, 0);
            System.exit(1);
        }

        DataOutputStream dataStream = new DataOutputStream(fileStream);

        do {
                try {
                    dataStream.writeChars(String.valueOf(count));
                   fileStream.flush();
                    count++;
                } catch (IOException e) {
                    LCD.drawString("Can't write to the file", 0, 1);
                    System.exit(1);
                }
        } while (count < 100);

        try {
            fileStream.close();
        } catch (IOException e) {
            LCD.drawString("Can't save the file", 0, 1);
            System.exit(1);
        }
    }

}

With this code I am basically trying to write numbers between 0 and 99 to a file called Test.txt. I don't know why, but the program is writting the data like this:

0 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 ...

As you can see, it is adding blank spaces between every digit. I've already tried many writting methods for the DataOutputStream, and dataStream.writeChars(String.valueOf(count)); was the "most successfull" one (other ones like writeInt(int b) write the data according to the ASCII table). I've also tried to use the BufferedOutputStream class, but I had no success. What I could possibly be doing wrong?


Solution

  • I solved the problem by simply substituting dataStream.writeChars(String.valueOf(count)) by dataStream.writeBytes(String.valueOf(count)).