Previous


1.1 Changes: ReverseTest Example

The ReverseTest example has three problems.

First, the ReverseTest example uses the DataInputStream.readLine method which has been deprecated in the JDK 1.1 because it does not convert correctly between bytes and characters. Most programs that use DataInputStream.readLine can make a simple change to use the same method from the new BufferedReader class instead. Simply replace code of the form:

DataInputStream d = new DataInputStream(in);
with:
BufferedReader d = new BufferedReader(new InputStreamReader(in));
ReverseTest is one of those programs which can make this simple change.

Second, ReverseTest explicitly creates a PrintStream for writing to the URLConnection. Using a PrintStream has been deprecated in favor of PrintWriter.

And finally, ReverseTest must call the new setDoOutput on its URLConnection to be able to write to the connection.

So, here is the new version of ReverseTest that fixes all of these problems:

import java.io.*;
import java.net.*;

public class ReverseTest {
    public static void main(String[] args) {
        try {
            if (args.length != 1) {
                System.err.println("Usage:  java ReverseTest string_to_reverse");
                System.exit(1);
            }
            String stringToReverse = URLEncoder.encode(args[0]);

            URL url = new URL("http://java.sun.com/cgi-bin/backwards");
            URLConnection connection = url.openConnection();
	    connection.setDoOutput(true);

            PrintWriter writer = new PrintWriter(connection.getOutputStream());
            writer.println("string=" + stringToReverse);
            writer.close();

            BufferedReader reader = new BufferedReader(
			new InputStreamReader(connection.getInputStream()));
            String inputLine;

            while ((inputLine = reader.readLine()) != null) {
                System.out.println(inputLine);
            }
            reader.close();
        } catch (MalformedURLException me) {
            System.err.println("MalformedURLException: " + me);
        } catch (IOException ioe) {
            System.err.println("IOException: " + ioe);
        }
    }
}


Previous