我正在尝试使用类RandomAccessFile,但字符串有问题。
这是第一部分。写入文件:
public static void main(String[] args) throws IOException {
File file = new File("/home/pep/java/randomFile.dat");
RandomAccessFile fitxerAleatori = new RandomAccessFile(file, "rw");
String[] surnames = { "SMITH",
"LOMU" };
int[] dep = { 10,
20 };
Double[] salary = { 1200.50,
1200.50 };
StringBuilder buffer = null;
int n = surnames.length;
for (int i = 0; i<n; i++){
randomFile.writeInt(i+1); //ID
buffer = new StringBuilder(surnames[i]);
buffer.setLength(10); //10 characters
randomFile.writeChars(buffer.toString());
randomFile.writeInt(dep[i]);
randomFile.writeDouble(salary[i]);
}
randomFile.close();
}
在第二部分中,我尝试读取此文件:
File file = new File("/home/pep/java/randomFile.dat");
RandomAccessFile randomFile = new RandomAccessFile(file, "r");
char[] surname = new char[10];
char aux;
int id, dep, pos;
Double salary;
pos = 0;
for (;;) {
randomFile.seek(pos);
id = randomFile.readInt();
for (int i = 0; i < surname.length; i++) {
aux = randomFile.readChar();
surname[i] = aux;
}
String surnameStr = new String(surname); //HERE IS THE PROBLEM!!
dep = randomFile.readInt();
salary = randomFile.readDouble();
System.out.println("ID: " + id + ", Surname: " + surnameStr + ", Departament: " + dep + ", Salary: " + salary);
pos = pos + 36; // 4 + 20 + 4 + 8
if (randomFile.getFilePointer() == randomFile.length())
break;
}
randomFile.close();
}
好吧,当我希望读到:
ID:1,姓氏:SMITH,部门:10,工资:1200.50
我收到了:
ID:1,姓氏:SMITH
就像在姓氏中是行尾一样,因为如果我不显示姓氏,则其他信息是正确的。
谢谢!
问题出在char数组中。我更改了de loop来读取字符:
for (int i = 0; i < surname.length; i++) {
aux = randomFile.readChar();
surname[i] = aux != 0 ? aux : ' ';
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句