我编写了一个自定义文件类型,我的 Java 程序中的数据被保存到其中。我想在 iPod/Pad/Phone 上获取数据。到目前为止,我编写了这个文件,用于从文件中读取海峡字节值并将它们更改为 NSStrings 和整数。
#import "BinaryFileReader.h"
@implementation BinaryFileReader
- (id)init {
self = [super init];
return self;
}
- (id)initWithLocation:(NSString*)filepath {
if ((self = [super init])) {
_file = [NSFileHandle fileHandleForReadingAtPath:filepath];
_fileOffset = 0;
if (_file == nil)
NSLog(@"%@%@",@"Failed to open file at path:",filepath);
}
return self;
}
- (void)close {
[_file closeFile];
}
- (int)readInt {
[_file seekToFileOffset:_fileOffset];
_databuffer = [_file readDataOfLength:4];
_fileOffset+=4;
return (int)[_databuffer bytes];
}
- (NSString*)readNSString {
int length = [self readInt];
[_file seekToFileOffset:_fileOffset];
_databuffer = [_file readDataOfLength:length];
_fileOffset+=length;
return [[NSString alloc] initWithData:_databuffer encoding:NSUTF8StringEncoding];
}
- (NSMutableArray*)readNSMutableArrayOfNSString {
NSMutableArray* array = [[NSMutableArray alloc] init];
int arrayLength = [self readInt];
int length;
for (int i=0; i<arrayLength; i++) {
length = [self readInt];
[_file seekToFileOffset:_fileOffset];
_databuffer = [_file readDataOfLength:length];
_fileOffset+=length;
[array addObject:[[NSString alloc] initWithData:_databuffer encoding:NSUTF8StringEncoding]];
}
return array;
}
@end
现在,当我尝试使用它来读取 NSStrings 或整数时,它没有得出正确的值。我假设由于 NSStrings 和整数都出现错误,这是 readInt 方法中的问题。有人看到我在这里错过的明显的东西吗?
编辑:
我尝试读取的文件格式以字符串开头。该字符串在使用 readNSString 读取时是正确的字符串,但缺少该字符串的前 1/3。
Java代码:
public void saveItem() {
try {
byte[] bytes;
FileOutputStream output;
if (countOccurrences(location.getPath(),'.')==1) {
System.out.println("Option 1");
output = new FileOutputStream(location+"/"+name+".dtb");
} else {
output = new FileOutputStream(location);
}
bytes = name.getBytes("UTF-8");
output.write(bytes.length);
output.write(bytes);
output.write(otherNames.length);
for (int i=0;i<otherNames.length;i++) {
bytes = otherNames[i].getBytes("UTF-8");
output.write(bytes.length);
output.write(bytes);
}
bytes = description.getBytes("UTF-8");
output.write(bytes.length);
output.write(bytes);
bytes = XactCode.getBytes("UTF-8");
output.write(bytes.length);
output.write(bytes);
bytes = SymbilityCode.getBytes("UTF-8");
output.write(bytes.length);
output.write(bytes);
output.write(averageLowPrice);
output.write(averageHighPrice);
output.write(averageLifeExpectancy);
output.close();
bytes = null;
} catch (Exception e) {
e.printStackTrace();
}
}