public
Last active

Reading ints from a file as binary and text

  • Download Gist
Main.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
import java.io.*;
import java.util.Random;
import java.util.Scanner;
 
public class Main
{
private static int DISK_BLOCK_SIZE = 4096;
private static int NUMBER_OF_INTS = 50000000;
 
public static void main(final String[] args) throws IOException
{
final File binaryFile = new File("input.dat");
final File textFile = new File("input.txt");
 
if (binaryFile.exists()) { binaryFile.delete(); }
binaryFile.createNewFile();
if (textFile.exists()) {textFile.delete(); }
textFile.createNewFile();
 
// here is the binary format file creation
final FileOutputStream fos = new FileOutputStream(binaryFile);
final BufferedOutputStream bos = new BufferedOutputStream(fos, DISK_BLOCK_SIZE);
final DataOutputStream dos = new DataOutputStream(bos);
 
// here is the text format file creation
final FileWriter fw = new FileWriter(textFile);
final BufferedWriter bfw = new BufferedWriter(fw, DISK_BLOCK_SIZE);
 
final Random rnd = new Random(System.currentTimeMillis());
int r;
for (int i = 0; i < NUMBER_OF_INTS; i++)
{
r = Math.abs(rnd.nextInt());
dos.write(r);
bfw.write(Integer.toString(r));
bfw.write(' ');
}
dos.close();
bos.close();
fos.close();
bfw.close();
fw.close();
 
// read them back in
final FileInputStream fis = new FileInputStream(binaryFile);
final BufferedInputStream bis = new BufferedInputStream(fis, DISK_BLOCK_SIZE);
final DataInputStream dis = new DataInputStream(bis);
 
final long brStart = System.currentTimeMillis();
 
while (dis.available() != 0)
{
dis.readInt();
}
 
System.out.printf("Read binary file in %04d ms\n", System.currentTimeMillis() - brStart);
 
dis.close();
bis.close();
fis.close();
 
final FileReader fr = new FileReader(textFile);
final BufferedReader bfr = new BufferedReader(fr, DISK_BLOCK_SIZE);
final Scanner scanner = new Scanner(bfr).useDelimiter(" ");
 
final long trStart = System.currentTimeMillis();
 
while(scanner.hasNext())
{
scanner.nextInt();
}
 
System.out.printf("Read text file in %04d ms\n", System.currentTimeMillis() - trStart);
 
scanner.close();
bfr.close();
fr.close();
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.