2012-10-05 47 views
11

Tôi có một số HashMap với hai Chuỗi Map<String, String> ldapContent = new HashMap<String, String>.Cách viết và đọc tệp bằng HashMap?

Bây giờ tôi muốn lưu Map trong một tập tin bên ngoài để sử dụng Map sau mà không cần khởi tạo nó một lần nữa ...

Vì vậy, làm thế nào tôi phải lưu Map sử dụng nó sau này nữa không?

+0

Bạn đã thử gì? Bạn có thể sử dụng tuần tự hóa Java, XML, CSV, dữ liệu nhị phân theo cách thủ công ... –

+0

Tôi chỉ biết trình xử lý đơn giản. do đó cảm ơn cho mẹo serialization. Tôi không biết nó trước ... –

Trả lời

15

HashMap thực hiện Serializable vì vậy bạn có thể sử dụng tuần tự thông thường để viết hashmap nộp

Dưới đây là liên kết cho Java - Serialization dụ

+0

ok cảm ơn, tôi sẽ thử nó. –

+0

hoàn hảo. nó hoạt động: D cảm ơn bạn rất nhiều !!! –

2

Bạn có thể viết một đối tượng vào một tập tin sử dụng writeObject trong ObjectOutputStream

ObjectOutputStream

31

Giải pháp đơn giản nhất mà tôi có thể nghĩ đến là sử dụng lớp Thuộc tính.

Tiết kiệm bản đồ:

Map<String, String> ldapContent = new HashMap<String, String>(); 
Properties properties = new Properties(); 

for (Map.Entry<String,String> entry : ldapContent.entrySet()) { 
    properties.put(entry.getKey(), entry.getValue()); 
} 

properties.store(new FileOutputStream("data.properties"), null); 

Đang tải bản đồ:

Map<String, String> ldapContent = new HashMap<String, String>(); 
Properties properties = new Properties(); 
properties.load(new FileInputStream("data.properties")); 

for (String key : properties.stringPropertyNames()) { 
    ldapContent.put(key, properties.get(key).toString()); 
} 

EDIT:

nếu bản đồ của bạn có chứa các giá trị rõ, họ sẽ được hiển thị nếu bạn mở tập tin dữ liệu thông qua bất kỳ trình soạn thảo văn bản, không phải là trường hợp nếu bạn tuần tự hóa bản đồ:

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser")); 
out.writeObject(ldapContent); 
out.close(); 
.210

EDIT2:

thay vì vòng lặp for (theo đề nghị của OldCurmudgeon) trong tiết kiệm dụ:

properties.putAll(ldapContent); 

Tuy nhiên, cho ví dụ tải này là tốt nhất có thể được thực hiện:

ldapContent = new HashMap<Object, Object>(properties); 
+2

Khi 'Properties' thực thi' Map', bạn có thể sử dụng 'putAll' để điền vào nó. Ngoài ra, vì 'HashMap' có một kiến ​​trúc' HashMap (Bản đồ m) ', bạn có thể điền nó vào xây dựng vì cùng một lý do. – OldCurmudgeon

+0

Tôi đồng ý, nó đơn giản hóa giải pháp – linski

+0

+1 cho mẫu mã. cảm ơn –

14

từ HashMap thực hiện giao diện Serializable, bạn có thể chỉ cần sử dụng ObjectOutputStream lớp để viết toàn bộ Map để gửi và đọc lại bằng cách sử dụng ObjectInputStream lớp

dưới mã đơn giản để giải thích việc sử dụng của ObjectOutStreamObjectInputStream

import java.util.*; 
import java.io.*; 
public class A{ 

    HashMap<String,String> hm; 
    public A(){ 
     hm=new HashMap<String,String>(); 

     hm.put("1","A"); 
     hm.put("2","B"); 
     hm.put("3","C"); 

     method1(hm); 

    } 

public void method1(HashMap<String,String> map){ 
    //write to file : "fileone" 
    try{ 
    File fileOne=new File("fileone"); 
    FileOutputStream fos=new FileOutputStream(fileOne); 
     ObjectOutputStream oos=new ObjectOutputStream(fos); 

     oos.writeObject(map); 
     oos.flush(); 
     oos.close(); 
     fos.close(); 
    }catch(Exception e){} 

    //read from file 
    try{ 
     File toRead=new File("fileone"); 
     FileInputStream fis=new FileInputStream(toRead); 
     ObjectInputStream ois=new ObjectInputStream(fis); 

     HashMap<String,String> mapInFile=(HashMap<String,String>)ois.readObject(); 

     ois.close(); 
     fis.close(); 
     //print All data in MAP 
     for(Map.Entry<String,String> m :mapInFile.entrySet()){ 
      System.out.println(m.getKey()+" : "+m.getValue()); 
     } 
    }catch(Exception e){} 
    } 

public static void main(String args[]){ 
     new A(); 
} 

} 

hoặc nếu bạn muốn ghi dữ liệu dưới dạng văn bản để nộp bạn chỉ có thể lặp qua Map và viết khoá và giá trị từng dòng, và đọc lại từng dòng và thêm vào HashMap

import java.util.*; 
import java.io.*; 
public class A{ 

    HashMap<String,String> hm; 
    public A(){ 
     hm=new HashMap<String,String>(); 

     hm.put("1","A"); 
     hm.put("2","B"); 
     hm.put("3","C"); 

     method2(hm); 

    } 

public void method2(HashMap<String,String> map){ 
    //write to file : "fileone" 
    try{ 
    File fileTwo=new File("filetwo.txt"); 
    FileOutputStream fos=new FileOutputStream(fileTwo); 
     PrintWriter pw=new PrintWriter(fos); 

     for(Map.Entry<String,String> m :map.entrySet()){ 
      pw.println(m.getKey()+"="+m.getValue()); 
     } 

     pw.flush(); 
     pw.close(); 
     fos.close(); 
    }catch(Exception e){} 

    //read from file 
    try{ 
     File toRead=new File("filetwo.txt"); 
     FileInputStream fis=new FileInputStream(toRead); 

     Scanner sc=new Scanner(fis); 

     HashMap<String,String> mapInFile=new HashMap<String,String>(); 

     //read data from file line by line: 
     String currentLine; 
     while(sc.hasNextLine()){ 
      currentLine=sc.nextLine(); 
      //now tokenize the currentLine: 
      StringTokenizer st=new StringTokenizer(currentLine,"=",false); 
      //put tokens ot currentLine in map 
      mapInFile.put(st.nextToken(),st.nextToken()); 
     } 
     fis.close(); 

     //print All data in MAP 
     for(Map.Entry<String,String> m :mapInFile.entrySet()){ 
      System.out.println(m.getKey()+" : "+m.getValue()); 
     } 
    }catch(Exception e){} 
    } 

public static void main(String args[]){ 
     new A(); 
} 

} 

LƯU Ý: trên mã có thể không phải là cách nhanh nhất để làm nhiệm vụ này, nhưng tôi muốn thể hiện một số ứng dụng của Clas ses

Xem ObjectOutputStream, ObjectInputStream, HashMap, Serializable, StringTokenizer

+0

+1 cho mã đầy đủ để kiểm tra, cảm ơn –

+1

chào mừng bạn @ user1671245, tôi đã cố gắng đưa ra ví dụ hoàn chỉnh và sử dụng một số lớp khác để hiển thị các cách khác nhau, tôi hy vọng nó sẽ giúp bạn – Farnabaz

Các vấn đề liên quan