c語言文件指針,文件指針操作

 2023-10-18 阅读 22 评论 0

摘要:?文件指針操作 1. getFilePointer方法 RandomAccessFile的讀寫操作都是基于指針的,也就是說總是在指針當前所指向的位置進行讀寫操作。RandomAccessFile提供了一個可以獲取當前指針位置的方法:long getFilePointer()RandomAccessFile在創建時默認指向文件開始(第一個字

?文件指針操作

1. getFilePointer方法

RandomAccessFile的讀寫操作都是基于指針的,也就是說總是在指針當前所指向的位置進行讀寫操作。
RandomAccessFile提供了一個可以獲取當前指針位置的方法:
long getFilePointer()
RandomAccessFile在創建時默認指向文件開始(第一個字節),通過getFilePointer方法獲取指針位置時值是"0"。
例如:

RandomAccessFile raf = new RandomAccessFile(file,”rw”);
System.out.println(raf.getFilePointer());//0
raf.write(‘A’);//寫出一個字節后,指針自動向后移動到下一個字節位置
System.out.println(raf.getFilePointer());//1
raf.writeInt(3);
System.out.println(raf.getFilePointer());//5
raf.close(); 

2. seek方法

c語言文件指針?RandomAccessFile的提供了一個方法用于移動指針位置。
void seek(long pos)
使用該方法可以移動指針到指定位置。
例如:

RandomAccessFile raf = new RandomAccessFile(file,”rw”);
System.out.println(raf.getFilePointer());//0
raf.write(‘A’);//指針位置1
raf.writeInt(3);//指針位置5
raf.seek(0);//將指針移動到文件開始處(第一個字節的位置)
System.out.println(raf.getFilePointer());//0
raf.close(); 

3. skipBytes方法

RandomAccessFile的提供了一個方法可以嘗試跳過輸入的 n 個字節以丟棄跳過的字節,方法定義為:
int skipBytes(int n)
該方法可能跳過一些較少數量的字節(可能包括零)。這可能由任意數量的條件引起;在跳過n個字節之前已到達文件的末尾只是其中的一種可能。此方法不拋出 EOFException。返回跳過的實際字節數。如果 n 為負數,則不跳過任何字節。

/*** 獲取游標位置以及對基本類型進行操作的方法* @author Administrator**/
class TestRandomAccessFileDemo{public static void main(String[] args) throws IOException {RandomAccessFile raf = new RandomAccessFile("data.bat", "rw");raf.write('a'); // 寫一個字節//將int最大值寫入文件
        raf.writeInt(Integer.MAX_VALUE); raf.writeDouble(3.141592612);System.out.println(raf.getFilePointer());//13/** RandomAccessFile 提供一個寫字符串的方法* 使UTF-8編碼將字符串轉換為字節后寫出* void writeUTF(String str)*/String str ="你好啊"; //24  UTF-8 多寫兩個字節
        raf.writeUTF(str);}}
class TestRandomAccessFileDemo7{public static void main(String[] args) throws IOException {RandomAccessFile raf = new RandomAccessFile("data.bat", "r");int d = raf.read();char c= (char)d;System.out.println(c);//aSystem.out.println(raf.getFilePointer());//1/** int readInt()* 連續讀取4個字節,并轉換為對應的int值*/int max =raf.readInt();System.out.println(max);//Integer.MAX_VALUE  2147483647
        System.out.println(raf.getFilePointer()); //5//跳過double 8字節raf.seek(13);String str =raf.readUTF();System.out.println(str);//你好啊//讀取double的內容raf.seek(5);double dou = raf.readDouble();System.out.println(dou);}
}
class TestRandomAccessFile8{public static void main(String[] args) throws IOException {/** 寫之前先將游標移動到文件末尾在進行寫操作* 這樣就是追加內容*/RandomAccessFile raf= new RandomAccessFile("append.txt", "rw");/** RandomAccessFile 同樣支持Length* 用于獲取文件的字節量*/raf.skipBytes(20); //跳過下面20個
        raf.seek(raf.length());raf.write("藥".getBytes("UTF-8"));raf.close();}
}

?

轉載于:https://www.cnblogs.com/manue1/p/4498009.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/147417.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息