您的位置:首页 > 编程语言 > Java开发

java22.IO操作------RandomAccessFile随机文件读写

2016-01-05 15:10 891 查看

一、写入:

示例:

线程代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class WriteFile extends Thread {

File file;
int block;
int L = 30;// 每个block有100字节数据

/**
* 1 2 3 4 5 6 |----------|----------|----------|----------|----------| 0xL
* 1xL
*
* 123455代表block
*
* @param f
* @param b
*/
public WriteFile(File f, int b) {
this.file = f;
this.block = b;
}

@Override
public void run() {
try {
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek((block - 1) * L);
raf.writeBytes("This is bolck" + block);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}


调用线程:

import java.io.File;

public class MultiWriteFile {

static File file = new File("test.txt");

public static void main(String[] args) {
if (file.exists()) {
file.delete();
}
new WriteFile(file, 1).start();
new WriteFile(file, 2).start();
new WriteFile(file, 3).start();
new WriteFile(file, 4).start();
new WriteFile(file, 5).start();
}

}


结果:



二、读取

示例:

将上述线程调用改为:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class WriteFile extends Thread {

File file;
int block;
int L = 30;// 每个block有100字节数据

/**
* 1 2 3 4 5 6 |----------|----------|----------|----------|----------| 0xL
* 1xL
*
* 123455代表block
*
* @param f
* @param b
*/
public WriteFile(File f, int b) {
this.file = f;
this.block = b;
}

@Override
public void run() {
try {
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek((block - 1) * L);
raf.writeBytes("This is bolck" + block);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}


结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: