2010-05-11 6 views
10

나는 Hashtable<string,string>을 가지고 있는데, 내 프로그램에서 나중에 처리 할 Hashtable의 값을 기록하고 싶다.해시 테이블을 파일에 쓸 수 있습니까?

내 질문은 : 우리는 파일에 개체를 쓸 수 있습니까? 그렇다면 나중에 어떻게 파일을로드 할 수 있습니까?

답변

9

예, 바이너리 직렬화 (ObjectOutputStream)를 사용하여 :

FileOutputStream fos = new FileOutputStream("t.tmp"); 
ObjectOutputStream oos = new ObjectOutputStream(fos); 

oos.writeObject(yourHashTable); 
oos.close(); 

은 그럼 당신은 ObjectInputStream

당신 안에 넣어 객체를 사용하여 읽을 수 Hashtable (또는 더 나은 - HashMap를) Serializable

를 구현해야

특정 응용 프로그램에 대해 알고하지 마십시오

FileOutputStream fos = new FileOutputStream("tmp.xml"); 
XMLEncoder e = new XMLEncoder(fos); 
e.writeObject(yourHashTable); 
e.close(); 
+0

답장 보내 주셔서 감사합니다. 내가 가진 질문 내 hastable <문자열 URL 문자열 urlcontent> 내가 좋아하는 파일을 XML로 쓸 수있는 방법을 //// //// tiendv

+0

XStream 또는 JAXB와 같은 것을 사용하여 xml을 사용자 정의 할 수 있지만 너무 많은 두통입니다. 나는 XMLEncoder 나 제안 된'Properties' 솔루션을 고수 할 것입니다. – Bozho

5

을, 그러나 당신은 Properties class 좀보고 할 수 있습니다 : 사람이 읽을 수있는 형식으로, 당신은 java.beans.XMLEncoder를 사용할 수 있습니다. (이 해시 맵을 확장합니다.)

이 클래스는

void load(InputStream inStream) 
    Reads a property list (key and element pairs) from the input byte stream. 
void load(Reader reader) 
    Reads a property list (key and element pairs) from the input character stream in a simple line-oriented format. 
void loadFromXML(InputStream in) 
    Loads all of the properties represented by the XML document on the specified input stream into this properties table. 
void store(Writer writer, String comments) 
     Writes this property list (key and element pairs) in this Properties table to the output character stream in a format suitable for using the load(Reader) method. 
void storeToXML(OutputStream os, String comment) 
     Emits an XML document representing all of the properties contained in this table. 

The tutorial도 매우 교육적을 제공합니다.

1

일단 작성된지도를 쉽게 편집하려면 jYaml을 살펴볼 수 있습니다. Yaml 형식의 파일에 쉽게 맵을 쓸 수 있으므로 읽고 편집하기 쉽습니다.

0

또한 MapDB을 사용할 수 있습니다 그리고 당신은 putcommit을 할 후에 당신을위한 HashMap에 저장됩니다. 그런 식으로 프로그램이 충돌하면 값은 계속 유지됩니다.

관련 문제