java - Strange symbols when using byte-based FileOutputStream, char-based FileWriter is OK -
task :
write java application creates file on local file system contains 10000 randomly generated integer values between 0 , 100000. try first using byte-based stream , instead using char-based stream. compare file sizes created 2 different approaches.
i made byte-based stream. after run program, in fileoutput weird symbols. doing 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 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 regular output file directly fileoutputsream that, need convert output bytes first. :
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(); }
Comments
Post a Comment