forked from bjmashibing/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomAccessFileTest.java
More file actions
71 lines (67 loc) · 2.24 KB
/
RandomAccessFileTest.java
File metadata and controls
71 lines (67 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* @author: 马士兵教育
* @create: 2019-09-28 16:20
*/
/**
* 分块读取文件
*
*/
public class RandomAccessFileTest {
public static void main(String[] args) {
File file = new File("doc.txt");
//整个文件的大小
long length = file.length();
//规定块的大小
int blockSize = 1024;
//文件可以被切分成多少个块
int size = (int)Math.ceil(length*1.0/blockSize);
System.out.printf("要被切成《%d》个块",size);
int beginPos = 0;
int actualSize = (int)(blockSize>length?length:blockSize);
for(int i = 0;i<size;i++){
//每次读取块的时候的起始偏移量
beginPos = i*blockSize;
if(i==size-1){
actualSize = (int) length;
}else{
actualSize = blockSize;
length -=actualSize;
}
System.out.println(i+"---》起始位置是:"+beginPos+"---->读取的大小是:"+actualSize);
// readSplit(i,beginPos,actualSize);
}
}
public static void readSplit(int i,int beginPos,int actualSize){
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(new File("doc.txt"),"r");
//表示从哪个偏移量开始读取数据
randomAccessFile.seek(beginPos);
byte[] bytes = new byte[1024];
int length = 0;
while((length = randomAccessFile.read(bytes))!=-1){
if(actualSize>length){
System.out.println(new String(bytes,0,length));
actualSize-=length;
}else{
System.out.println(new String(bytes,0,actualSize));
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
randomAccessFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}