Search code examples
javatext-filesbytestream

Writing to a file using a byte stream


I'm trying to write a series of 10000 random integers to a text file using a byte stream, however once I open the text file up it has a collection of random characters which seemingly have little to do with the integer values I want to be shown. I'm new to this form of stream, I'm guessing that the integer values are being taken as byte values, but I can't think of a way to get round this.

My current attempt...

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;


public class Question1ByteStream {
    public static void main(String[] args) throws IOException {

        FileOutputStream out = new FileOutputStream("ByteStream.txt");

        try {
            for(int i = 0; i < 10000; i ++){
                Integer randomNumber = randInt(0, 100000);
                int by = randomNumber.byteValue();
                out.write(by);
            }
        }finally{
            if (out != null) {
                out.close();
            }
        }
    }

    public static int randInt(int min, int max) {
        Random rand = new Random();
        int randomNum = rand.nextInt((max - min) + 1) + min;

        return randomNum;
    }
}

Apologies if this lacks clarity.


Solution

  • It's because the numbers that you write are not written as strings into the txt but as raw byte value. 
    Try the following code:
    
      BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter("./output.txt"));
            writer.write(yourRandomNumberOfTypeInteger.toString());
        } catch (IOException e) {
            System.err.println(e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    System.err.println(e);
                }
            }
        }
    
    Or, if referring to your original code, write the Integer directly:
    try {
                for(int i = 0; i < 10000; i ++){
                    Integer randomNumber = randInt(0, 100000);
                    out.write(randomNumber.toString());
                }
            }finally{
                if (out != null) {
                    out.close();
                }
            }