在另一个类中获取字符串以填充查询

时间:2014-05-21 17:59:20

标签: java string properties google-analytics-api

最近我试图通过属性文件填充Google查询,我写了这些代码行:

public String getPropValues() throws IOException {

    String result = "";
    Properties prop = new Properties();
    String propFileName = "config.properties";

    InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
    prop.load(inputStream);
    if (inputStream == null) {
        throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
    }

    Date time = new Date(System.currentTimeMillis());

    // Get the property value and print it out
    String user = prop.getProperty("user");
    String company1 = prop.getProperty("startDate");
    String company2 = prop.getProperty("endDate");
    String company3 = prop.getProperty("company3");

    result = "Company List = " + company1 + ", " + company2 + ", " + company3;
    System.out.println(result + "\nProgram Ran on " + time + " by user=" + user);
    return result;
}

从属性中获取数据

private static GaData executeDataQuery(Analytics analytics, String profileId) throws IOException {
    return analytics.data().ga().get("ga:" + profileId, // Table Id. ga: + profile id.
        "2014-05-19", // Start date.
        "2014-05-20", // End date.
        "ga:pageviews,ga:sessions,ga:uniquePageviews") // Metrics.
        .setDimensions("ga:date")
        .setSort("-ga:date")
        .setMaxResults(25)
        .execute();
}

这是我正在使用的查询,所以如何制作它以便我可以在属性文件中输入日期,以便将它链接到我的查询中的字段?

1 个答案:

答案 0 :(得分:1)

您必须将日期作为字符串读取,然后将其转换为日期。

有两种方法可以实现(超过2种,但这两种是最常见的方式):

  • 保存属性文件中的毫秒数,然后将该属性读取为Long并将其转换为Date:Date date = new Date(long_value);

  • 保存格式化日期:2014/05/21,然后在您的文件中解析:How to parse a date?

例如:

    String company1 = prop.getProperty("startDate");
    // suppose that compan1 has the value 2014-05-21

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Date result =  df.parse(company1);  
    System.out.println(result);