文件读写(2)
int与byte[]之间的互相转化
使用java.nio.ByteBuffer类可以完成int到
byte[]的转换
byte[] buf = new byte[4];
int a = 0x12345678;
ByteBuffer enc = ByteBuffer.wrap(buf);
enc.putInt(a);
可以发现,buf中的4个字节为: 12 34 56 78
反过程:把byte[]->int
ByteBuffer dec = ByteBuffer.wrap(buf);
运行结果如下:
int与byte[]之间的互相转化
使用java.nio.ByteBuffer类可以完成int到
byte[]的转换
byte[] buf = new byte[4];
int a = 0x12345678;
ByteBuffer enc = ByteBuffer.wrap(buf);
enc.putInt(a);
可以发现,buf中的4个字节为: 12 34 56 78
反过程:把byte[]->int
ByteBuffer dec = ByteBuffer.wrap(buf);
int value = dec.getInt();
代码如下:
package my;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
public class HelloWorld
{
public static void write(byte[] data,int off,int size) {
File filename=new File("c:/example/haha");
try {
FileOutputStream fout=new FileOutputStream(filename);
fout.write(data, off, size);
fout.close();
}catch(IOException e) {
e.printStackTrace();
}
}
public static int read(byte[] buf) {
int count=0;
File filename=new File("c:/example/haha");
try {
FileInputStream fin=new FileInputStream(filename);
count=fin.read(buf);
fin.close();
}catch(IOException e) {
e.printStackTrace();
}
return count;
}
public static void main(String[] args)
{
// byte[] buf=new byte[4];
// int a=0x12345678;
// ByteBuffer enc=ByteBuffer.wrap(buf);
// enc.putInt(a);
// int size=enc.position();
// write(buf,0,size);
//
// byte[] buf_read=new byte[1024];
// int count_read=read(buf_read);
// ByteBuffer srcbuf=ByteBuffer.wrap(buf_read,0,count_read);
// int n=srcbuf.getInt();
// System.out.println("读取到的int值为:"+n);
// System.out.println("exit");
//把String写入文件中
int id=0x00000001;
String name="球球";
String phone="15656565656";
byte[] buf=new byte[1024];
ByteBuffer dstbuf=ByteBuffer.wrap(buf);
dstbuf.putInt(id); //放入ID
try {
byte[] s1=name.getBytes("GBK");
byte[] s2=phone.getBytes("GBK");
dstbuf.put(s1);
dstbuf.put(s2);
}catch(Exception e) {
e.printStackTrace();
}
int total=dstbuf.position();
write(buf,0,total);
System.out.println("exit");
}
}
运行结果如下: