【发布时间】:2019-01-26 13:28:58
【问题描述】:
我的目标是读取文本文件中的行并在文件中寻找一个位置,然后使用 java 中的 randomaccessfile IO 从该位置读取字符串到给定长度。我编写了以下代码,我的代码将无限循环并始终打印第一行。下面是代码。有人能帮我吗? 封装测试;
import java.io.RandomAccessFile;
import java.util.LinkedHashMap;
import java.util.Map;
public class MyTest {
static byte[] b;
static Map<String, Integer> pos = new LinkedHashMap<>();
static Map<String, Integer> length = new LinkedHashMap<>();
static RandomAccessFile raf;
static String str = null;
public static void main(String[] args) throws Exception {
pos.put("name", 0);
pos.put("age", 3);
pos.put("gender", 8);
length.put("name", 2);
length.put("age", 6);
length.put("gender", 10);
raf = new RandomAccessFile("mytext", "r");
while ((str = raf.readLine()) != null) {
for (Map.Entry<String, Integer> map : pos.entrySet()) {
String key = map.getKey();
read("mytext", map.getValue(), length.get(key));
}
}
}
public static void read(String path, int position, int length) throws Exception {
b = new byte[500];
raf.seek(position);
raf.read(b, position, length);
System.out.println(new String(b));
}
}
【问题讨论】: