/**
*该测试用来测试IOUtil类中的方法:
*publicstaticStringreadString(RandomAccessFileraf,intlength)throwsException{
*/
publicclassPart4{
/**
*从给定的RandomAccessFile当前位置开始连续
*读取length个字节,并转换为字符串后返回
*转换字符串时使用的字符集为:ISO8859-1
*需要注意,由于业务逻辑要求,所以RandomAccessFile
*使用完毕后不要关闭。
*@paramraf
*@paramlength
*@return
*@throwsException
*/
publicstaticStringreadString(RandomAccessFileraf,intlength)throwsException{
byte[]buf=newbyte[length];
intlen=raf.read(buf);
Stringstr=newString(buf,0,length,"ISO8859-1");
raf.close();//此处需要close吗?close会出现什么问题?不close会出现什么问题?
returnstr;
}
publicstaticvoidmain(String[]args){
try{
/*
*该测试文件中32个字节表示的字符串为lidz,剩余
*字符全部为空格。
*/
RandomAccessFileraf=newRandomAccessFile("src/test/resources/test.dat","r");
Stringstr=readString(raf,32);
/*
*应当输出:
*内容:lidz
*/
System.out.println("内容:"+str.trim());
}catch(Exceptione){
e.printStackTrace();
}
}
}
分 -->
|