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 |
/* Write int to a file using DataOutputStream This Java example shows how to write a Java integer primitive value to a file using writeInt method of Java DataOutputStream class. */ import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException; public class WriteIntToFile { public static void main(String[] args) { String strFilePath = "C://FileIO//WriteInt.txt"; try { //create FileOutputStream object FileOutputStream fos = new FileOutputStream(strFilePath); /* * To create DataOutputStream object from FileOutputStream use, * DataOutputStream(OutputStream os) constructor. * */ DataOutputStream dos = new DataOutputStream(fos); int i = 100; /* * To write an int value to a file, use * void writeInt(int i) method of Java DataOutputStream class. * * This method writes specified int to output stream as 4 bytes value. */ dos.writeInt(i); /* * To close DataOutputStream use, * void close() method. * */ dos.close(); } catch (IOException e) { System.out.println("IOException : " + e); } } } |
This is neat and is quite useful, but it very slow in cases where a number needs to be written to a file (as data) thousands of times. Is there a faster alternative short of reading the bits of an int or float individually?