【发布时间】:2010-03-04 21:23:11
【问题描述】:
我有一个文件,它由一行组成:
1 , 1 2 , 1 3 6 , 4 ,...
在此表示中,空格分隔整数和逗号。 这个字符串太大了,我无法用 RandomAccessFile.readLine() 读取它(几乎需要 4 Gb)。所以我创建了一个缓冲区,它可以包含 10 个整数。我的任务是对字符串中的所有整数进行排序。
你能帮忙吗?
编辑
@奥斯卡雷耶斯
我需要将一些整数序列写入文件,然后从中读取。其实我不知道,该怎么做。我是新手。所以我决定用chars来写整数,整数之间的分隔符是“,”,序列之间的分隔符是“\n\r”。所以我创造了一个能读它的怪物:
public BinaryRow getFilledBuffer(String filePath, long offset) throws IOException{
mainFile = new RandomAccessFile(filePath, "r");
if (mainFile.length() == 0){
return new BinaryRow();
}
StringBuilder str = new StringBuilder();
mainFile.seek(mainFile.length()-4); //that is "\n" symbol
char chN = mainFile.readChar();
mainFile.seek(offset);
int i = 0;
char nextChar = mainFile.readChar();
while (i < 11 && nextChar != chN){
str.append(nextChar);
if (nextChar == ','){
i++;
if (i == 10){
break;
}
}
nextChar = mainFile.readChar();
}
if (nextChar == chN){
position = -1;
}else{
position = mainFile.getFilePointer();
}
BinaryRow br = new BinaryRow();
StringBuilder temp = new StringBuilder();
for (int j = 0; j < str.length(); j++){
if ((str.charAt(j) != ',')){
temp.append(str.charAt(j));
if (j == str.length() - 1){
br.add(Integer.parseInt(temp.toString()));
}
}else{
br.add(Integer.parseInt(temp.toString()));
temp.delete(0, temp.length());
}
}
mainFile.close();
return br;
}
如果你能建议怎么做,请做 =)
【问题讨论】:
-
你的代码哪里出了问题?您尝试了哪些方法?
-
是的,要将这些整数写入我使用 RandomAccessFile.writeChars() 的文件。我尝试使用 writeInt() 但整数粘在一起...所以 writeChars() 以这种方式写入整数,我只添加了逗号...
-
@Dmitry: 将号码
136放在一起有什么问题,你为什么需要它作为1 3 6? -
我现在迷路了,你的输入和期望的输出是什么?
-
期望的输入是:1,2,4,5,6,7 3,8,9 那是一个文件的表示(有两个序列)。我需要添加它们(在结果序列中应该是两个序列中的整数而不重复,并且结果序列必须排序)。期望的输出:1,2,3,4,5,6,7,8,9 那是另一个文件 - resultFile.
标签: java sorting external-sorting