一、写入:
示例:
线程代码:
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();
}
}
}
结果: