本帖最后由 了无尘 于 2012-3-31 01:13 编辑
如果是256你需要把它转换成字节,即写进去2个字节,一般的包装流之类的都是这么干的,只不过他们内部都有不同解码方式- 256
- 00000000 00000000 00000001 00000000
复制代码- import java.io.IOException;
- import java.io.RandomAccessFile;
- public class Test
- {
- public static void main(String[] args) throws Exception
- {
- RandomAccessFile rdf = new RandomAccessFile("abc.txt","rw");
- writeInt(rdf, 256);
- rdf.close();
-
- RandomAccessFile rd = new RandomAccessFile("abc.txt","rw");
- byte[] bytes = new byte[]{(byte)rd.read(),(byte)rd.read(),(byte)rd.read(),(byte)rd.read()};
- System.out.println(readInt(rdf, bytes));
- System.out.print(byteToBin(bytes[0]));
- System.out.print(byteToBin(bytes[1]));
- System.out.print(byteToBin(bytes[2]));
- System.out.println(byteToBin(bytes[3]));
- }
-
- public static void writeInt(RandomAccessFile rdf,int i) throws IOException
- {
- byte[] bytes = new byte[]{
- (byte) (i>>24),
- (byte) ((i>>16) & 0xff),
- (byte) ((i>>8) & 0xff),
- (byte) (i & 0xff)
- };
-
- for (byte b : bytes)
- {
- rdf.write(b);
- }
- }
-
- public static String byteToBin(byte b)
- {
- StringBuffer sb = new StringBuffer();
- byte t = b;
- for(int i = 0; i < 8; i++, t=(byte)(t>>1))
- {
- sb.append(t%2);
- }
- return sb.reverse().toString() + " ";
- }
-
- public static int readInt(RandomAccessFile rdf,byte[] bytes)
- {
- return (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3];
- }
- }
复制代码 |