Java高级语法笔记-文件读写(2)

文件读写(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 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");
		
	}
}

运行结果如下:




评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT1995

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值