-1

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

zomdar
  • 263
  • 2
  • 6
  • 22
  • You're badly mixing up System.out and pw as the target for your write operations, as far as I can see you just perform println's (ie, write newlines to it) on pw... – fvu May 14 '14 at 16:30
  • ok so i guess closing it would help? pw.close() – zomdar May 14 '14 at 16:38
  • Read my comment again: if you perform a set of `System.out.printf(column + ", ");` followed by a `pw.println();` where do you think the data will actually be written? Yes, you need to `pw.close();` the file, but **until you actually write something to that file** you will just be closing an empty file... – fvu May 14 '14 at 16:55
  • How about this: just replace `System.out.printf(column + ", ");` with `pw.printf(column + ", ");` and for good measure add `pw.close();` after the writing was done. – fvu May 14 '14 at 17:19
  • ok so i did that but the only issue that i am having is that only the first value shows up on the csv file and not the rest of them any ideas? – zomdar May 14 '14 at 17:27
  • Does `GaData results` contain more than one line? It might be helpful to *add* your revised code *after* the existing codeblock (ie, do not erase the existing codeblock as your original question won't make much sense without the existing code. – fvu May 14 '14 at 17:29
  • ok cool just did that any ideas? – zomdar May 14 '14 at 17:41
  • OK that explains a lot - you need just 1 close, after the final write. But I am puzzled, are you sure this code actually prints one record to the output file? It should crash and burn on the second write attempt as you already closed the output file. Please clarify that point and I'll formulate a complete answer afterwards. – fvu May 14 '14 at 17:46

2 Answers2

0

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

    }

}
fvu
  • 32,488
  • 6
  • 61
  • 79
  • oh wow thanks i just check this and the one that i came up with is simialr to this......thanks so much for the help and thank you interwebs – zomdar May 14 '14 at 20:31
  • definatley would have never found out about that part where prints null w.o your help – zomdar May 14 '14 at 20:33
  • @user3634077 well it took some time and effort, but I'm glad if my code helped you. Good luck with your project. – fvu May 14 '14 at 20:46
-1

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

  • OP wants the data from `GaData results` to end up in that csv file... He just has to write them to `pw` instead of `System.out`. – fvu May 14 '14 at 16:59
  • hmm yes this did help me understand how this writing thing works but i am having a hard time incorporating your explanation into my code where i print some stuff – zomdar May 14 '14 at 17:14
  • Despite this answer being accepted by OP: OP clearly states in the question title " Using PrintWriter to extract Google analytics data ***to CSV file***". Except for OP's confusion between `pw` and `System.out` and the lacking `close()` OP's code is actually correct. Your answer is factually correct, but unrelated to OP's question and seems just to habe managed to conuse OP even more than he already was. – fvu May 14 '14 at 17:25
  • Well, I often use Google Analytics and I understood that OP wanted to screen-print analytics' reports, which have been exported in .csv. I hope I haven't misunderstood the question – Giacomo Fabris May 14 '14 at 17:28