阅读json文件以及如何更改硬编码路径

时间:2014-11-19 02:02:16

标签: java json

问题:我想更改硬编码的json文件路径。路径将来自detailsListHM,但我不知道该怎么做。

这是我的主程序

 public class Program {
     // hard coding json file path
     private static final String filePath = "C:/appSession.json";

     public static void main(String[] args) 
     {
         taskManager();
     }
     public static void taskManager() 
     {
         detailsHM = jsonParser(filePath);
     }
    public static HashMap<String, String> jsonParser(String jsonFilePath) 
    {

         HashMap<String, String> detailsHM = new HashMap<String, String>();
         String refGene = "";

         try {
            // read the json file
            FileReader reader = new FileReader(filePath);
         } catch (FileNotFoundException ex) {
            ex.printStackTrace();
         }
    }
}

这是另一个名为CustomConfiguration

的类
 public class CustomConfiguration {
    private static HashMap<String, String> detailsListHM =new HashMap<String,String>();

    public static void readConfig(String a) {
        //read from config.properties file

        try {
            String result = "";
            Properties properties = new Properties();
            String propFileName = a;

            InputStream inputStream = new FileInputStream(propFileName);

            properties.load(inputStream);
            // get the property value and print it out
            String lofreqPath = properties.getProperty("lofreqPath");
            String bamFilePath = properties.getProperty("bamFilePath");
            String bamFilePath2 = properties.getProperty("bamFilePath2");
            String resultPath = properties.getProperty("resultPath");
            String refGenPath = properties.getProperty("refGenPath");
            String filePath = properties.getProperty("filePath");


            Set keySet = properties.keySet();
            List keyList = new ArrayList(keySet);
            Collections.sort(keyList);
            Iterator itr = keyList.iterator();

            while (itr.hasNext()) {

               String key = (String) itr.next();
               String value = properties.getProperty(key.toString());


               detailsListHM.put(key, value);
           }

    } catch (IOException ex) {
        System.err.println("CustomConfiguration - readConfig():" + ex.getMessage());
    }

}

public static HashMap<String, String> getConfigHM() {
     return detailsListHM;
}

2 个答案:

答案 0 :(得分:0)

添加新的属性调用&#34; json-filepath&#34;并阅读

String filePath = properties.getProperty("json-filepath");

因此,即使在运行时,最终用户也可以更改json文件路径。

答案 1 :(得分:0)

您可以使用主要参数传递filePath参数。

public static void main(String[] args) {
    String filePath = null;
    if(args.length > 0) {
        filePath = args[0]; 
    }
}

然后像这样调用你的主类:

java Program C:/appSession.json