java學習第22天--IO綜合練習題集錦3
來源:互聯網
上載者:User
long型資料和它的原生數組相互轉換 /* * long型資料和它的原生數組相互轉換 * */ public class Demo {
public static void main(String[] args) { long n = Long.MAX_VALUE; System.out.println(n);
byte[] buf = long2Bytes(n); long res = bytes2Long(buf); System.out.println(res);
// for (byte b : buf) { // System.out.println(b);//127 // }
}
//byte[] --> long:高位在前 public static long bytes2Long(byte[] buf){ long l0 = (buf[0] & 0xFFL)<< 56; long l1 = (buf[1] & 0xFFL)<< 48; long l2 = (buf[2] & 0xFFL)<< 40; long l3 = (buf[3] & 0xFFL)<< 32; long l4 = (buf[4] & 0xFFL)<< 24; long l5 = (buf[5] & 0xFFL)<< 16; long l6 = (buf[6] & 0xFFL)<< 8; long l7 = (buf[7] & 0xFFL)<< 0;
return l0 + l1 + l2 + l3 + l4 + l5 + l6 + l7; }
//long --> byte[]:高位在前 public static byte[] long2Bytes(long n){ byte[] buf = new byte[8]; buf[0] = (byte)(n >> 56); buf[1] = (byte)(n >> 48); buf[2] = (byte)(n >> 40); buf[3] = (byte)(n >> 32); buf[4] = (byte)(n >> 24); buf[5] = (byte)(n >> 16); buf[6] = (byte)(n >> 8); buf[7] = (byte)(n >> 0);//127
return buf; }
}
隨機訪問檔案:RandomAccessFile 此類的執行個體支援對隨機訪問檔案的讀取和寫入隨機訪問檔案的行為類似儲存在檔案系統中的一個大型 byte 數組存在指向該隱含數組的游標或索引,稱為檔案指標;輸入操作從檔案指標開始讀取位元組,並隨著對位元組的讀取而前移此檔案指標。 構造方法: RandomAccessFile(File file, String mode) RandomAccessFile(String name, String mode) 讀寫方法: 可以讀寫多種常見類型資料 特殊方法: void seek(long pos)
隨機訪問檔案(只做簡單瞭解)
import java.io.RandomAccessFile; /* * RandomAccessFile(File file,String mode) * RandomAccessFile(String name,String mode) */ public class RandomAccessFileDemo { public static void main(String[] args ) throws Exception { RandomAccessFile raf = new RandomAccessFile( "raf.txt" , "rw" ); raf .writeInt(200); // 移動檔案指標到檔案頭 raf .seek(0); int i = raf .readInt(); System . out .println( i ); raf .close(); } }
import java.io.RandomAccessFile; /* * 隨機訪問檔案父類是 Object. * 可以進行讀和寫兩種操作 . * 在構造方法中指定對檔案操作的模式 : * 一般使用 :" rw ", 表示既可以讀 , 又可以寫 . * RandomAccessFile(File file,String mode) * RandomAccessFile(String name,String mode) */ public class RandomAccessFileDemo2 { public static void main(String[] args ) throws Exception { // 建立對象 RandomAccessFile raf = new RandomAccessFile( "raf.txt" , "rw" ); // 寫出資料 raf .write(97); System. out .println( raf .getFilePointer()); raf .writeInt(200); System. out .println( raf .getFilePointer()); raf .writeUTF( "hello" ); System. out .println( raf .getFilePointer()); raf .writeUTF( "world" ); System. out .println( raf .getFilePointer()); // 定位到字串位移量 // raf.seek(12); // // // 讀一個字串 , 讀取方法要和將要讀取的真實資料類型配套 // String s = raf.readUTF(); // System.out.println(s); // 多次讀取指定的字串 for ( int i = 0; i <5; i ++){ raf .seek(12); System. out .println( raf .readUTF()); } // 釋放資源 raf .close(); } }
隨機訪問檔案中有一個字串,如何?對字串多次讀取?
Properties 類 不屬於 io 包下 , 但是由於某些操作和 io 流相關 , 所以放到 io 這裡講解,當成 Map 的子類使用 : 主要是添加元素及遍曆 特有方法 : setProperty //設定配置內容 getProperty //擷取配置內容 stringPropertyNames