java中I/O流中的隨機流
阿新 • • 發佈:2019-01-22
隨機流要實現RandomAccessFile這個方法
RandomAccessFile raf = new RandomAccessFile(“D:/IOTest/helloworld.txt”, “r”);讀資料第二個引數是“r”寫資料第二個引數是“rw”
//讀資料
public class RandomDemo {
/**
* 斷點續傳 暫停後,可以從原來的地方接著繼續傳 多執行緒 斷點下載 分塊下載
*
* @param args
*/
public static void main(String[] args) {
// 建立一個 隨機流的物件
try {
// 使用dataInputStream
RandomAccessFile raf = new RandomAccessFile(
"D:/IOTest/helloworld.txt", "r");
char c = 0;
raf.seek(2048);
System.out.println("檔案指標" + raf.getFilePointer());
byte[] buf = new byte [1024];
int len = 0;
while ((len = raf.read(buf)) != -1) {
System.out.println(new String(buf, 0, len));
System.out.println("檔案指標" + raf.getFilePointer());
}
//下面使用char來實現的和上面一樣
// while ((c = raf.readChar()) != -1) {
// System.out.print(c);
// System.out.println("檔案指標" + raf.getFilePointer());
// }
} catch (Exception e) {
e.printStackTrace();
}
}
}
//寫資料
public static void main(String[] args) {
try {
RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");
raf.writeUTF("你好,隨機流");
raf.writeUTF("你好,隨機流");
raf.writeUTF("你好,隨機流");
raf.writeUTF("你好,隨機流");
raf.writeUTF("你好,隨機流");
raf.writeUTF("你好,隨機流");
raf.writeUTF("你好,隨機流");
raf.writeUTF("你好,隨機流");
raf.writeUTF("你好,隨機流");
// 讀
raf.seek(0);// 跳到頭
// System.out.println(raf.readBoolean());
// System.out.println(raf.readChar());
// System.out.println(raf.readDouble());
// System.out.println(raf.readUTF());
// 最後面插入
// 跳到最後
raf.seek(raf.length());
raf.writeUTF("插入到最後");
// 插入到中間,從指定位置開始插入
raf.seek(20);
raf.writeUTF("插入到中間");
} catch (Exception e) {
e.printStackTrace();
}
}