使用PrintWriter将Google Analytics数据提取到CSV文件

时间:2014-05-14 16:24:03

标签: java csv google-analytics filewriter printwriter

大家好我试图使用printwriter通过JAVA从谷歌分析中提取数据

原始代码

private static void printGaData(GaData results) {

   //csv printer
   PrintWriter pw = null;
   try {
     pw = new PrintWriter(new BufferedWriter(new FileWriter("data.csv")));
     }
     catch(Exception e) {
     e.printStackTrace();
     }

   //getting the queries to print

    if (results.getRows() == null || results.getRows().isEmpty()) {
      System.out.println("No results Found.");
    } else {

      // Print column headers.
      for (ColumnHeaders header : results.getColumnHeaders()) {
        System.out.printf(header.getName() + ", ");
      }
      pw.println();

      // Print actual data.
      for (List<String> row : results.getRows()) {
        for (String column : row) {
          System.out.printf(column + ", ");
        }
        pw.println();
      } 

      pw.println();

    }

  }
}

它没有给我一个错误,但是当我打开csv文件时,那里什么都没有

编辑:

好吧所以我已经得到它打印的东西,但唯一的问题是,当我打印GaData时,只有一个变量出现,例如ga:pageviews

继承我的查询

  private static GaData executeDataQuery(Analytics analytics, String profileId) throws IOException {
return analytics.data().ga().get("ga:" + profileId, // Table Id. ga: + profile id.
    "today", // Start date.
    "today", // End date.
    "ga:pageviews, ga:visits, ga:uniquePageviews") // Metrics.
    .setDimensions("")
    .setSort("-ga:visits")
    .setFilters("ga:medium==organic")
    .setMaxResults(25)
    .execute();

}

这是我编辑的用于提取数据的代码

    private static void printGaData(GaData results) {

 //csv printer
   PrintWriter pw = null;
   try {
     pw = new PrintWriter(new BufferedWriter(new FileWriter("data.csv")));
     }
     catch(Exception e) {
     e.printStackTrace();
     }

   //getting the queries to print

    if (results.getRows() == null || results.getRows().isEmpty()) {
      pw.printf("No results Found.");
      pw.close();
    } else {

      // Print column headers.
      for (ColumnHeaders header : results.getColumnHeaders()) {
        pw.printf(header.getName() + ", ");
        pw.close();
      }
      pw.println();
      pw.close();

      // Print actual data.
      for (List<String> row : results.getRows()) {
        for (String column : row) {
          pw.printf(column + ", ");
          pw.close();
        }
        pw.println();
        pw.close();
      } 
      pw.println();
      pw.close();

    }

  }
}

感谢所有帮助,我对java / programming

非常陌生

2 个答案:

答案 0 :(得分:0)

根据迄今为止的讨论,您的(第二)代码的改编版本,侧重于解决我可以发现的直接问题:

  • pw.close()只需在最后一次打印操作后完成一次
  • 如果文件无法打开,则无法继续
  • 将“无数据”消息写入csv文件可能不是最佳解决方案
  • 因为您的代码不使用printf的设施,所以最好只使用print / println

private static void printGaData(GaData results) {

    //csv printer
    PrintWriter pw = null;
    try {
        pw = new PrintWriter(new BufferedWriter(new FileWriter("data.csv")));
    } catch (Exception e) {
        System.out.println("I could not open the output csv file, see stacktrace below:");
        e.printStackTrace();
    }

    // If pw is still null here, the PrintWriter is not available and continuing would be pointless
    if (pw==null) {
        return;
    }

    //getting the queries to print
    if (results.getRows() == null || results.getRows().isEmpty()) {
        // Although technically not ''wrong'', using printf here is not the best solution
        pw.println("No results Found.");
        // But it might be better to just write that message in the output window, and not in the csv file
        System.out.println("No results Found.");
    } else {

        // Print column headers.
        for (ColumnHeaders header : results.getColumnHeaders()) {
            pw.print(header.getName() + ", ");
        }
        pw.println();

        // Print actual data.
        for (List<String> row : results.getRows()) {
            for (String column : row) {
                pw.print(column + ", "); // that space after , is not needed and might even cause problems for some programs that are supposed to read the csv file
            }
            pw.println();
        }
        // ok, all done, close that PrintWriter
        pw.close();

    }

}

答案 1 :(得分:-1)

您正在混合作家读者

  • 您需要一个Reader / InputStream来获取输入数据
  • 您需要Writer / OutputStream来编写输出数据

所以,首先你需要阅读data.csv。您可以使用InputStreamReader,然后换入BufferedReaderBufferedInputStream。在这个例子中,我将使用Readers,因为我认为它们更容易处理文本文件。

BufferedReader br = new BufferedReader (new FileReader (new File ("data.csv")));

然后,您阅读每一行

String buf;
while ((buf=br.readLine())!=null){
   String [] row = buf.split (",");
   //Do whatever you want with your row. You can also save it in a List
}

如果您想要打印文件的内容,您只需打印每一行 - System.out.println(row)

如果要将行写入另一个文件,那么您需要一个编写器。包装在BufferedWriter中的FileWriter应该没问题。 当然,你可以使用你想要的每一位作家。它取决于你在做什么。 PrintWriter也行。无论如何,记得刷新并关闭每个Writer / OutputStream,并且关闭每个Reader / InputStream。

希望这会有所帮助。 贾科莫