只是一个建议,如果您想使持久化信息的形式更加健壮,您可以考虑对象序列化。这比听起来容易。只需有一个实现 Serializable 的静态内部类,如下所示:
static class JunkRec implements Serializable
{
private static final long serialVersionUID = 1L;
final int _blockID, _blockX, _blockY;
final String _filePath, _fileName;
public JunkRec(int blockID, int blockX, int blockY,
String filePath, String fileName)
{
_blockID = blockID;
_blockX = blockX;
_blockY = blockY;
_filePath = filePath;
_fileName = fileName;
}
@Override
public String toString() {
return String.format("id=%08d x=%04d y=%04d fp=%s fn=%s",
_blockID, _blockX, _blockY, _filePath, _fileName);
}
}
现在,一种存储 JunkRec 的方法...
public static void storeJunk(JunkRec jr)
{
try (
FileOutputStream fos = new FileOutputStream(
jr._filePath + jr._fileName + ".ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);) {
oos.writeObject(jr);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
给定文件名的另一种恢复 JunkRec 的方法。
public static JunkRec retrieveJunk(String filePath, String fileName)
{
try (
FileInputStream fis = new FileInputStream(
filePath + fileName + ".ser");
ObjectInputStream ois = new ObjectInputStream(fis);) {
return (JunkRec) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
最后是 main() 中的一个小测试驱动程序...
public static void main(String[] args)
{
// generate and restore 10 records
Random r = new Random();
List<String> names = new ArrayList<>();
/* do a few in two ways */
for (int i = 0; i < 5; ++i) {
int blk = r.nextInt(10000);
String fname = String.format("BLKID_%02d", i);
if (names.add(fname)) {
JunkRec jr = new JunkRec(
r.nextInt(10000),
r.nextInt(50),
r.nextInt(50),
"/tmp/",
fname);
storeJunk(jr);
System.out.println("Wrote: "+jr);
}
}
/* read them all back */
for (String fname : names) {
JunkRec jr = retrieveJunk("/tmp/", fname);
System.out.println("Retrieved: " + jr + " from " + fname);
}
/* clean up */
for (String fname : names) {
((File) new File("/tmp/" + fname + ".ser")).delete();
}
}
这不是生产质量的代码,但它显示了序列化是多么容易。有一个陷阱,但总的来说,序列化是基于文件的持久性的可靠解决方案。
只是一个建议。 玩得开心!