[英]Writing to a file using a byte stream
我正在嘗試使用字節流向文本文件中寫入一系列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;
}
}
很抱歉,如果這不夠清楚。
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();
}
}
不要像下面那樣(以字節字符形式書寫)
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()
方法,並將其寫入文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.