我编写了这些函数,以使用尽可能少的字节数将int值写入文件。但是一行由于某种原因而读取了错误的值(请参阅注释)。
File f = new File("data.txt");
RandomAccessFile raf = new RandomAccessFile(f, "rw");
raf.writeBytes(toByte(4321,3)); // convert 4321 to ascii
raf.seek(0);
System.out.println(fromByte(raf.readLine())); // convert back
// convert integer to ascii String for i < 16,777,216
// let b=1 for i<256, b=2 for i<256*256, b=3 for i<256*256*256
private static String toByte(int i, int b){
if (b==3) // 3 bytes
return "" + (char)(i/65536) + (char)(i%65536/256) + (char)(i%256);
if (b==2) // 2 bytes
return "" + (char)(i/256) + (char)(i%256);
else // 1 byte
return "" + (char)i;
}
// convert ascii string to integer for s.length = {1,2,3}
private static int fromByte(String s){
int i = 0;
if (s.length()==3)
i = (int)s.charAt(0)*65536 +
(int)s.charAt(1)*256 +
(int)s.charAt(2);//------------> 65533? should be 225!
else if (s.length()==2)
i = (int)s.charAt(0)*256 +
(int)s.charAt(1);
else
i = (int)s.charAt(0);
return i;
}
输出为69629,但应为4321。