任务 :
我做了基于字节的流。运行该程序后,在fileOutput中我得到了一些奇怪的符号。难道我做错了什么 ?
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
public class Bytebased {
public static void main(String[] args) throws IOException {
File outFile = new File( "fileOutput.txt" );
FileOutputStream fos = new FileOutputStream(outFile);
Random rand = new Random();
int x;
for(int i=1;i<=10001;i++){
x = rand.nextInt(10001);
fos.write(x);
}
fos.close();
}
}
当我使用基于字符的流时,它可以工作:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class Charbased {
public static void main(String[] args) throws IOException {
File outFile = new File( "fileOutput2.txt" );
FileWriter fw = new FileWriter(outFile);
Random rand = new Random();
int x;
String y;
for(int i=1;i<=10001;i++){
x = rand.nextInt(10001);
y=x + " ";
fw.write(y);
}
fw.close();
}
}
最佳答案
直接从FileOutputSream将常规输出写入文件可以做到这一点,您需要首先将输出转换为字节。
就像是 :
public static void main(String[] args) throws IOException {
File outFile = new File( "fileOutput.txt" );
FileOutputStream fos = new FileOutputStream(outFile);
String numbers = "";
Random rand = new Random();
for(int i=1;i<=10001;i++){
numbers += rand.nextInt(10001);
}
byte[] bytesArray = numbers.getBytes();
fos.write(bytesArray);
fos.flush();
fos.close();
}