Java高级语法笔记-文件读写(2)
生活随笔
收集整理的這篇文章主要介紹了
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與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); //放入IDtry {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");} }運行結果如下:
總結
以上是生活随笔為你收集整理的Java高级语法笔记-文件读写(2)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C/C++判断是否为笔记本电脑
- 下一篇: Java高级语法笔记-自定义异常类