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

Integer Object randomNumber に対して自動的にtoString()メソッドが呼び出され、ファイルに書き込まれます。

于 2014-05-11T15:04:45.980 に答える