Task :
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.
I made the byte-based stream. After I run this program, in fileOutput I get some weird symbols. 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'm using 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();
}
}
Writing a regular output to a file directly from a FileOutputSream will do that, you need to convert your output into bytes first. Something like :
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With