伙计们!
我无法使用RandomAccessFile
.
这是一个简单的程序,它使用这种格式将信息写入特定文件(西里尔字母):
keyLength, valueLength, key, value
然后程序尝试读取此信息,但我的输出不正确:
writing success
keyLength = 10, valueLength = 4
read: килло, гр
UPD 预期输出:
writing success
keyLength = 10, valueLength = 4
read: киллограмм, сала
问题是什么?(除了我脑袋小的问题)
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String fileName = "file.db";
RandomAccessFile outputFile = null;
try {
outputFile = new RandomAccessFile(fileName, "rw");
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
System.exit(1);
}
String key = "киллограмм";
String value = "сала";
try {
outputFile.writeInt(key.length());
outputFile.writeInt(value.length());
outputFile.write(key.getBytes("UTF-8"));
outputFile.write(value.getBytes("UTF-8"));
} catch (IOException e) {
System.err.println(e.getMessage());
System.exit(1);
}
System.out.println("writing success");
RandomAccessFile inputFile = null;
try {
inputFile = new RandomAccessFile(fileName, "r");
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
System.exit(1);
}
int keyLength = 0, valueLength = 0;
try {
keyLength = inputFile.readInt();
valueLength = inputFile.readInt();
} catch (IOException e) {
System.err.println(e.getMessage());
}
System.out.println("keyLength = " + keyLength + ", valueLength = " + valueLength);
if (keyLength <= 0 || valueLength <= 0) {
System.err.println("key or value length is negative");
System.exit(1);
}
byte[] keyBytes = null, valueBytes = null;
try {
keyBytes = new byte[keyLength];
valueBytes = new byte[valueLength];
} catch (OutOfMemoryError e) {
System.err.println(e.getMessage());
System.exit(1);
}
try {
inputFile.read(keyBytes);
inputFile.read(valueBytes);
} catch (IOException e) {
System.err.println(e.getMessage());
System.exit(1);
}
try {
System.out.println("read: " + new String(keyBytes, "UTF-8") + ", " + new String(valueBytes, "UTF-8"));
} catch (IOException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
}