java奇怪的符号当使用基于字节的FileOutputStream时,基于字符的FileWriter是可以的
任务:
Write a Java application that creates a file on your local file system which contains 10000 randomly generated integer values between 0 and 100000. Try this first using a byte-based stream and then instead by using a char-based stream. Compare the file sizes created by the two different approaches.
我制作了基于字节的流。在我运行这个程序之后,在文件输出中我得到了一些奇怪的符号。我做错什么了吗
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();
}
}
# 1 楼答案
直接从FileOutputSream将常规输出写入文件将完成此操作,您需要首先将输出转换为字节。 比如: