日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

          歡迎訪問 生活随笔!

          生活随笔

          當前位置: 首頁 > 编程语言 > java >内容正文

          java

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

          發布時間:2025/3/15 java 36 豆豆
          生活随笔 收集整理的這篇文章主要介紹了 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); //放入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)的全部內容,希望文章能夠幫你解決所遇到的問題。

          如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。