좀 더 강력한 형식의 영구 정보를 만들고 싶다면 객체 직렬화를 고려해보십시오. 그것은 소리보다 쉽습니다. 파일 이름 지정,
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를 복원하는 또 다른 방법 : 그냥이 같은 정적 내부 Serializable를 구현 클래스, 뭔가가있다.
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;
}
그리고) (주에서 마지막으로 약간의 테스트 드라이버
은 ...
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();
}
}
이없는 생산 품질의 코드는하지만 쉽게 직렬화 될 수있는 방법을 보여줍니다. 문제가 있지만 일반적으로 직렬화는 파일 기반 지속성을위한 견고한 솔루션입니다.
그냥 제안. 재미있게 보내세요!
대단히 감사합니다. 나는 네가 제안한 것을 했어. 나는 또한 당신이 진술 한 다른 것들을하기 위해 노력할 것입니다, 대단히 감사합니다. :) – FireRaven