使用字节流写入文件

时间:2014-05-11 14:53:50

标签: java text-files bytestream

我尝试使用字节流将一系列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;
    }
}

如果缺乏明确性,请道歉。

2 个答案:

答案 0 :(得分: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();
            }
        }

答案 1 :(得分: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()方法 它将写入文件。