質問

Hello all i am trying to use the printwriter to extract data from google analytics via JAVA

original code

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();

    }

  }
}

it does not give me an error but however when i open the csv file there is nothing in there

EDIT:

ok so i have gotten it to print something but the only problem is that when i print the GaData only one variable shows up for example, ga:pageviews

heres my query

  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();

}

Here is my edited code to extract the data

    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();

    }

  }
}

Thanks for all the help i am very new to java/programming

役に立ちましたか?

解決

Based on the discussion so far an adapted version of your (second) code, that focuses on fixing the immediate problems I could spot:

  • pw.close() needs to be done just once, after the last print operation
  • if the file failed to open you cannot continue
  • writing the " no data" message to the csv file may not be the best solution
  • because your code does not use printf's facilities it's better to just use 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();

    }

}

他のヒント

You are mixing writers and readers.

  • You need a Reader/InputStream to get input data
  • You need a Writer/OutputStream to write output data

So, first you need to read from data.csv. You can either use an InputStream or a Reader, and wrap in a BufferedReader or in a BufferedInputStream. In this example I'll use Readers, because I think they are simpler to handle text files.

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

Then, you read each line

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
}

If you want to print file's content, you can simply println every row -System.out.println(row)

If you want to write rows into another file, then you'll need a writer. A FileWriter wrapped in a BufferedWriter should be fine. Of course, you can use every writer you want. It depens on what you are doing. PrintWriter is also OK. Anyway, remember to flush and close every Writer/OutputStream, and to close every Reader/InputStream.

Hopes this helps. Giacomo

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top