0

我正在尝试使用字节流将一系列 10000 个随机整数写入文本文件,但是一旦我打开文本文件,它就会有一组随机字符,这些字符似乎与我想要的整数值无关显示。我是这种流形式的新手,我猜整数值被视为字节值,但我想不出一种方法来解决这个问题。

我目前的尝试...

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

抱歉,如果这缺乏清晰度。

4

2 回答 2

1
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();
            }
        }
于 2014-05-11T15:01:47.203 回答
0

不要像下面那样(以字节字符的形式写)

 for(int i = 0; i < 10000; i ++){
                Integer randomNumber = randInt(0, 100000);
                int by = randomNumber.byteValue();
                out.write(by);
}

以字符串的形式写入,因为它是一个文本文件

 for(int i = 0; i < 10000; i ++){
                Integer randomNumber = randInt(0, 100000);

                out.write(randomNumber);
}

将为整数对象 randomNumber 调用自动toString()方法,并将其写入文件。

于 2014-05-11T15:04:45.980 回答