java多种方式读写文件
???????ReadFromFile.readFileByRandomAccess(filetxt);
??? }
}
??????????? line++;
??????????? }
??????????? reader.close();
??????????? } catch(IOException e) {
??????????????? e.printStackTrace();
??????????????? } finally {
??????????????????? if (reader != null){
??????????????????????? try {
???????????????????????????reader.close();
??????????????????????? } catch (IOException e1) {
??????????????????????? }
??????????????????? }
??????????????????? System.out.println("");
??????????????? }
??????? }
??????? /**
??????? * 随机读取文件内容readFileByRandomAccess
??????? * @paramfileName
??????? */
??????? public static void readFileByRandomAccess(String fileName){
??????????? RandomAccessFile randomFile =null;
????????? ??try {
??????????????? System.out.println("随机读取一段文件内容:");
??????????????? // 打开一个随机访问文件流,按只读方式
??????????????? randomFile = new RandomAccessFile(fileName, "r");
??????????????? // 文件长度,字节数
??????????????? longfileLength = randomFile.length();
?????????? ?????// 读文件的起始位置
??????????????? intbeginIndex = (fileLength > 4) ? 4 : 0;
??????????????? //将读文件的开始位置移到beginIndex位置。
??????????????? randomFile.seek(beginIndex);
??????????????? byte[]bytes = new byte[10];
??????????????? intbyteread = 0;
???????????? ???//一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
??????????????? //将一次读取的字节数赋给byteread
??????????????? while((byteread = randomFile.read(bytes)) != -1){
???????????????????System.out.write(bytes, 0, byteread);
??????????????? }
??????????? } catch(IOException e){
??????????????? e.printStackTrace();
??????????? } finally {
??????????????? if(randomFile != null){
??????????????????? try {
???????????????????????randomFile.close();
??????????????????? } catch (IOException e1) {
??????????????????? }
??????????????? }
??????????? }
??????? }
???????
??? }
?