2014-03-26 17 views
2

我有一個更新文件(只有一個特定行)的要求,它包含鍵值形式的值。以鍵值形式更新具有值的java文件

app.num_hosts=4 
app.resourceid=broker0 

我打算讀取地圖中的所有文件,然後修改特定字段並重寫該文件。這是更新文件的好方法嗎?我可以使用哪種API將地圖寫入文件?

通過搜索現有的問題,我無法找到一種方法來更新只是單行而不重寫整個文件。

+0

你能提供的示例文件,所以我們可以看到它的結構? –

+0

增加了一些示例值 – zer0Id0l

+0

是.properties擴展名的文件嗎?如果是的話,去http://www.mkyong.com/java/java-properties-file-examples/ – iMBMT

回答

3

聽起來像你基本上想要使用java.util.properties庫。

public static void main(String[] args) { 

    Properties prop = new Properties(); 
    OutputStream output = null; 

    try { 
     //load the file into properties object 
     FileInputStream input = new FileInputStream("config.properties");  
     prop.load(input); 
     input.close(); 

     // set the properties value 
     output = new FileOutputStream("config.properties"); 
     prop.setProperty("app.num_hosts", "4"); 
     prop.setProperty("app.resourceid", "broker0"); 
     prop.store(output, null); 


    } catch (IOException io) { 
     io.printStackTrace(); 
    } finally { 
     if (output != null) { 
      try { 
       output.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

    } 
} 

blog post進一步概括它,但你的會想要做的是首先讀取屬性文件,使您的更新,然後將它寫回。

+0

即使我的屬性文件不是以'config.properties'命名,而是'config.layout',它會工作嗎? – zer0Id0l

+0

我相信它應該,但我不是100%。 Theres一種方式找出;) – NSjonas

+0

謝謝..試試吧! :) – zer0Id0l

1

一個與Java Properties

其他明智的,可替代的選擇辦法是,你可以使用IO的API和手動更新它象下面這樣:

1)創建一個映射,它有key和value要要在文件中更新。

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

2)讀取路徑的文件,因爲它給你真正的路徑即戰/ fileName.layout

String filepath = getServletContext().getRealPath("fileName.layout"); 

3)創建一個方法,它讀取文件並替換值,返回修改字符串。

public static String getreportPdfString(HashMap<String, String> replaceValesMap,String fileppath){ 
    String generatedString = ""; 
    File file = new File(fileppath); 
     StringBuffer strContent = new StringBuffer(""); 
     FileInputStream fin = null; 
     try { 
      fin = new FileInputStream(file); 
      int ch; 
     while ((ch = fin.read()) != -1) 
      strContent.append((char) ch); 
      fin.close(); 
     } catch (Exception e) { 
      System.out.println(e); 
     } 
     String fileString= strContent.toString(); 
     for (Map.Entry<String, String> entry : replaceValesMap.entrySet()) { 
      fileString = StringUtils.replace(fileString, entry.getKey(),entry.getValue()); 
     } 

    return fileString; 

} 

4)最後寫入文件:

try (PrintStream out = new PrintStream(new FileOutputStream("fileName.layout"))) { 
    out.print(text); 
}