Tag Archives: java.io

Getting the HTTP headers from an URL



Introduction

In an other article we already read from the URL. In this example only the HTTP headers are read using the same URL object:

try {
    // Create a URLConnection object for a URL
    URL url = new URL("http://hostname:80");
    URLConnection conn = url.openConnection();

    // List all the response headers from the
    // server.
    // Note: The first call to
    // getHeaderFieldKey() will implicit send
    // the HTTP request to the server.
    for (int i=0; ; i++) {
        String headerName =
        conn.getHeaderFieldKey(i);
        String headerValue =
        conn.getHeaderField(i);
        if (headerName == null && 
            headerValue == null) {
            // No more headers
            break;
        }
        if (headerName == null) {
            // The header value contains the
              server's HTTP version
        }
    }
} catch (Exception e) {
}

 

Write To a File

Introduction

We had a few methods of writing text to a file. The method shown below is the most popular. It  uses a method for writing which uses the java.io.FileWriter class. Note that this class has a constructor which can take two arguments. The filename and a Boolean. When you specify this as true, the FileWriter will append the ouput to the end of the file (if it exists already). You should give the full path to the file. On Windows you should escape the backslash (\), since it is the Java escape character. A file in Windows should therefore look like C:\\path\\to\\my\\file.txt. UNIX and Linux don’t need this. On Windows you can also use UNIX notation; e.g; C:/path/to/my/file.txt.

OutputStreams must always be closed.

try {
    BufferedWriter out = new BufferedWriter(new FileWriter("outfilename"));
    out.write("the String to write");
    out.close();
} catch (IOException e) {
}

 

Writing UTF-8 encoded text to a file

Introduction

UTF-8 I s a variable width character encoding capable of encoding all 1,112,064 valid code points in Unicode using one to four 8-bit bytes. The encoding is defined by the Unicode standard. When you want to write UTF-8 from your Application you can use the code below.

try {
    Writer out = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream("outfilename"), "UTF8"));
    out.write(aString);
    out.close();
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
}