String str = "大家好!!!!!!!!!!!!!!!!!";
byte[] strData = str.getBytes("UTF-8");
raf.writeInt(strData.length);
raf.write(strData);
讀取文件中的字節數組可以調用read(byte[] b)方法,先創建一個字節數組strArr,通過調用read(strArr)方法將字節存入strArr中,再通過String的構造方法String(byte[] b,String
charsetName),將字節數組轉換爲字符串int lenth=raf.readInt();
byte[] strData=new byte[lenth];
raf.read(strData);
String str=new String(strData,"UTF-8");
System.out.println(str);
5,RandomAccessFile的對應基本數據類型的序列化方法有writeInt(int v),writeLong(long v),writeDouble(double v)等。對應的RandomAccessFile的對應基本數據類型的反序列化方法有readInt(),readLong(),readDouble()等。
import java.io.RandomAccessFile;
/**
* 複製文件
*
* @author Earl 2014-2-7下午03:26:13
*
*/
public class RandomAccessFileDemo06 {
public static void main(String[] args)throws Exception {
//用於讀取源文件
RandomAccessFile src=new RandomAccessFile("JDK.CHM","r");
//用於寫入目標文件
RandomAccessFile des=new RandomAccessFile("JDKCOPY.CHM","rw");
long start=System.currentTimeMillis();
int d=-1;
while((d=src.read())!=-1){
des.write(d);
}
long end=System.currentTimeMillis();
System.out.println("複製完畢");
System.out.println("複製用時:"+(end-start));
}
}
以上代碼是不使用緩衝數組的方法,該方法複製速度慢,下面使用帶緩衝的方法import java.io.RandomAccessFile;
/**
* 基於緩存的複製文件操作
*
* @author Earl 2014-2-7下午04:19:15
*
*/
public class RandomAccessFileDemo07 {
public static void main(String[] args) throws Exception {
RandomAccessFile src = new RandomAccessFile("JDK.CHM", "r");
RandomAccessFile des = new RandomAccessFile("JDKCOPY2.CHM", "rw");
// 創建一個字節數組
byte[] buffer = new byte[1024 * 10];//並不是緩存區越大速度越快
// 保存實際讀取到的字節數
int len = -1;
long start=System.currentTimeMillis();
while ((len = src.read(buffer)) > 0) {
/*
* void write(byte[] b,int start,int len):
* 將給定的字節數組中從start處開始連續將len個字節寫出
*/
des.write(buffer, 0, len);
}
long end=System.currentTimeMillis();
System.out.println("複製完畢");
System.out.println("用時"+(end-start)+"毫秒");
src.close();
des.close();
}
}