Skip to content

Commit 4bc2cbc

Browse files
committed
新增:RandomAccessFile的使用案例
1 parent 0d95534 commit 4bc2cbc

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package org.javacore.io;
2+
3+
import java.io.FileNotFoundException;
4+
import java.io.IOException;
5+
import java.io.RandomAccessFile;
6+
7+
/*
8+
* Copyright [2015] [Jeff Lee]
9+
*
10+
* Licensed under the Apache License, Version 2.0 (the "License");
11+
* you may not use this file except in compliance with the License.
12+
* You may obtain a copy of the License at
13+
*
14+
* http://www.apache.org/licenses/LICENSE-2.0
15+
*
16+
* Unless required by applicable law or agreed to in writing, software
17+
* distributed under the License is distributed on an "AS IS" BASIS,
18+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19+
* See the License for the specific language governing permissions and
20+
* limitations under the License.
21+
*/
22+
23+
/**
24+
* @author Jeff Lee
25+
* @since 2015-9-28 18:50:22
26+
* RandomAccessFile的使用案例
27+
*/
28+
public class UsingRandomAccessFile {
29+
// 文件名
30+
static String file = "rtest.bat";
31+
32+
static void display() throws IOException {
33+
// 创建随机访问类,只读模式
34+
RandomAccessFile rf = new RandomAccessFile(file, "r");
35+
for (int i = 0; i < 7; i++)
36+
System.out.println("Value " + i + ": " + rf.readDouble());// 读取一个Double
37+
System.out.println(rf.readUTF());// 读取一个字符串
38+
rf.close();
39+
}
40+
41+
public static void main(String[] args) throws IOException {
42+
// 创建随机访问类,读写模式
43+
RandomAccessFile rf = new RandomAccessFile(file, "rw");
44+
for (int i = 0; i < 7; i++)
45+
rf.writeDouble( i * 1.123);// 写入一个Double
46+
rf.writeUTF("文件结束");// 写入一个字符串
47+
rf.close();
48+
49+
display();
50+
51+
rf = new RandomAccessFile(file, "rw");
52+
rf.seek(5 * 8);// 设置文件指针偏移量
53+
rf.writeDouble(47.003);
54+
rf.close();
55+
56+
display();
57+
}
58+
}

0 commit comments

Comments
 (0)