Task:
Write a Java application that creates a file on the local file system that contains 10,000 randomly generated integer values between 0 and 100,000. Try this first using a byte stream and then using a char based stream. Compare file sizes created by two different approaches.
I created a byte stream. After running this program, in fileOutput I get some strange characters. Am I doing something wrong?
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(); } }
When I use a char based stream, it works:
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(); } }
source share