Printing console output

Hello,
I’m trying to build a small sketch asking a website some weather data. Unfortunately, the site I’m asking data to throws back a 403 error and Processing seems not able to work. So I tried in this way, editing some code I found on the web:

// import libraries
import java.net.*;
import java.io.*;

URL url;

//Create a writer to print the console out
PrintWriter output = createWriter("weatherText.txt");

//
try {

  // Create a URL object
  url = new URL("URL-OF-THE-WEBSITE");
  URLConnection conn = url.openConnection();
  conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB;     rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.30729)");
  // Read all of the text returned by the HTTP server
  BufferedReader in = new BufferedReader
    (new InputStreamReader(conn.getInputStream(), "UTF-8"));

  String htmlText;

  while ( (htmlText = in.readLine ()) != null) {
    System.out.println(htmlText);
  }
  in.close();
} 

//Should be called once the website throws 403 back, case 1
catch (MalformedURLException e) {
  e.printStackTrace(output);
  System.out.println(output.toString());
} 

//Should be called once the website throws 403 back, case 2
catch (IOException e) {
  e.printStackTrace(output);
  System.out.println(output.toString());
}

//Clearing and closing after the job is done 
finally {
  output.flush(); 
  output.close(); 
  exit();
}

The console seems ok with all the text I want to work on. I now need to take the text in the console and save it in the file I create (weatherText.txt, which is correctly generated), but the file is empty.

May you kindly help me to figure out how to solve this issue?

you need to output to the PrintWriter :slight_smile:

output.println(htmlText);

Hello micuat,
the code you suggest is already included in line 24 of my sketch. I guess the issue arises in one of the two “catch” statement after that. There (lines 32 and 38) I wrote

  System.out.println(output.toString());

but replacing it with your code I have

        The variable "htmlText" does not exist

I think I have not properly defined local/global variables… any suggestion?

what you have is

System.out.println(htmlText);

which outputs to the console.

What I suggest is

output.println(htmlText);

to write to output object (the variable name may be confusing!)

Whoops think I forgot to check the output :sweat_smile:
Your solution works fine!

Can you please be so kind to address me to any resource/tutorial to go deeper in the print/println/printWriter stuff?

Thank you.

no problem!

basics are here
https://processing.org/reference/PrintWriter.html

if you want more info
https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html