我目前正在开发一个程序,该程序需要使用RandomAccessFile来写入文件,然后才能读回来。 我的写功能: NAME,LOCATION,TYPE是最终的整数,具有该类型的长度(以字节为单位),用于查找写入位置。我已经尝试过更改它,所以它只是从它停止的地方写入但是这会对我造成影响而根本不会写入。
for(int k=0;k<tab.length;k++){
for(int l=0;l<tab[k].length;l++){
int endRec = k*(NAME + LOCATION + TYPE); //used to get to the end of the last record written
tables.seek(endRec);
if(l==0){
tables.writeUTF(tab[k][l]); //writes just first attribute of record
}
else if(l==1){
tables.seek(endRec + NAME); //goes to end of last record, then goes to end of first attribute
tables.writeUTF(tab[k][l]); //writes second attribute
}
else if(l==2){
int hold = Integer.parseInt(tab[k][l]); //used to convert string from array to integer ie, "21" to 21
tables.seek(endRec + NAME + LOCATION); //goes to end of last record then past first two attributes
tables.writeInt(hold); //writes third and last attribute
}
}
}
我的阅读功能(未完成它现在会在测试模式下阅读更多内容):
RandomAccessFile readIn;
byte[] Name = new byte[NAME];
byte[] Location = new byte[LOCATION];
byte[] TName = new byte[TNAME];
try{
readIn = new RandomAccessFile("sys_library.tab", "r");
readIn.read(Name);
readIn.read(Location);
int readType = readIn.readInt();
String readName = new String(Name, "UTF-8");
String readLocation = new String(Location, "UTF-8");
System.out.printf("%20s%132s%8s%n", readName, readLocation, readType);
readIn.close();
}
catch(IOException e){
throw new RuntimeException(e);
}
然而,当它读入并输出时,它输出的白色方框可能导致字符串被切断。整数打印很好,这只是我的字符串凌乱。将byte []转换为字符串有不同的方法吗? 一个例子是它输出(方形)(方形)sys_library.ta,它应该只是sys_library.tab但是它正在增加。