Strange characters when using FileOutputStream, char based FileWriter bytes in order

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(); } } 
+6
source share
1 answer

Writing regular output to a file directly from FileOutputSream will do this; you need to convert your output to bytes first. Sort of:

 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(); } 
+2
source

Source: https://habr.com/ru/post/986979/


All Articles