|
|||
Department of Engineering | |
University of Cambridge > Engineering Department > computing help |
import java.io.*; class Program3 { public static void main(String[] args) throws Exception { PrintStream pstream; FileOutputStream fstream; File myfile; myfile= new File("abcde"); fstream = new FileOutputStream(myfile); pstream = new PrintStream(fstream); pstream.println("hello"); } }The File object gives us a way to refer to the file that's on disc. myfile.length() would tell you the file-length. The FileOutputStream object sets up a path from the program to the file. The PrintStream object gives us better control over using this path. We can reduce the number of intermediate variables by using
PrintStream pstream = new PrintStream( new FileOutputStream("abcde"));if we're just interested in I/O and not in changing the file's characteristics.
import java.io.*; class Program6 { public static void main(String[] args) throws Exception { BufferedReader keyboard; String line; keyboard = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Type a few characters then press Enter"); System.out.flush(); line= keyboard.readLine(); System.out.println("You typed: " + line); } }The System.out.flush() command is to ensure that the prompt is displayed before the program waits for input.
To read an integer, first read in a string s then use Integer.parseInt(s) to convert it. Reading a floating point number is harder: first read in a string s then use Double.valueOf(s).doubleValue() to convert it.
Reading across the internet in C++ would require much work. In Java it's
relatively easy to do (though not easy to fully understand). The package
to use is java.net. The following reads the first 10 lines
of a local WWW page.
import java.net.*;
import java.io.*;
class Program7 {
public static void main(String[] args) throws Exception {
URL u= new URL("http://www-h.eng.cam.ac.uk/help/tpl/languages/java.html");
URLConnection c= u.openConnection();
InputStreamReader reader = new InputStreamReader(c.getInputStream());
BufferedReader cuedjavapage = new BufferedReader(reader);
for (int i=0;i<10;i++)
System.out.println(cuedjavapage.readLine());
}
}
The StreamTokenizer class help cope with the task of parsing an input file.
In the example below, input that's typed in is classified.
import java.io.*;
class Tokens {
public static void main(String[] args) throws Exception {
Reader r = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer tok = new StreamTokenizer(r);
tok.quoteChar('"'); // string delimiter
try {
while (tok.nextToken() != tok.TT_EOF) {
System.out.print("Line:" + tok.lineno() + ":");
switch (tok.ttype) {
case StreamTokenizer.TT_NUMBER:
System.out.println("Number: " + tok.nval);
break;
case StreamTokenizer.TT_EOL:
System.out.println("End of the line");
break;
case StreamTokenizer.TT_WORD:
System.out.println("Word: " + tok.sval);
break;
default:
System.out.println("Token: " + tok.toString());
break;
}
}
}
catch (IOException e) {}
}
}
import java.io.*; class Program1 { public static int get_seven() { return 7; } public static void main(String[] args) { int foo; try { foo=get_seven(); } catch (Exception e) { System.err.println("An error has happened"); } int bar=foo; } }The problem is that when the compiler reaches the int bar=foo; line it doesn't know whether an exception has happened, so it doesn't know whether foo is set or not.
An interface declares a list of publically available methods
and constants, but doesn't state where (in what class) the implementation
of the methods are. interfaces are created and used rather in the same way
as classes are
public interface Music {
public static final int = 999;
public abstract void play();
}
class Player extends Applet implements Music {
public void play() {
...
A class can implement an interface (as in Program6)
or several interfaces. If it does so it has to at least claim that it's
supplying the implementation. Note that implementing an interface has
some similarities with extending a class with abstract methods -
in both situations the new class has to provide an implementation. However,
extending a class implies inheriting its data structures and non-abstract
methods too.
Here's a simple example of using interfaces
interface legs {
public abstract int number_of_legs();
};
interface wings {
public abstract int number_of_wings();
};
class Pegasus implements legs, wings {
public int number_of_legs() { return 4;}
public int number_of_wings() { return 2;}
}
class Inter {
public static void main(String[] args) {
Pegasus p= new Pegasus();
System.out.println("p has " + p.number_of_legs() + " legs and " + p.number_of_wings() + " wings.");
}
}
Graphics toolkits use interfaces. For example, in the AWT, there's an interface called MouseListener which has methods that are called when a mouse-button's pressed, etc. A class that wants to respond to mouse activity could implement this interface but would then have to provide code for all the methods - mouseClicked(MouseEvent e), etc. An alternative is to extend the MouseAdapter abstract class. This already implements the MouseListener interface (providing null methods) so the programmer needs to provide code only for the methods that interest them.
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Swing1 { public static void main(String s[]) { JFrame frame = new JFrame("Demo1"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); JLabel myLabel = new JLabel("Just a demo"); myLabel.setPreferredSize(new Dimension(175, 100)); frame.getContentPane().add(myLabel, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } }
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Swing2 { public static void main(String s[]) { JFrame frame = new JFrame("Demo1"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.out.println("Window closed"); System.exit(0); } }); JPanel panel1 = new JPanel(); panel1.setLayout(new BorderLayout()); frame.getContentPane().add(panel1, BorderLayout.NORTH); JPanel panel2 = new JPanel(); panel2.setLayout(new BorderLayout()); frame.getContentPane().add(panel2, BorderLayout.SOUTH); JLabel myLabel = new JLabel("centred"); panel2.add(myLabel, BorderLayout.CENTER); JLabel myLabel2 = new JLabel("down"); panel2.add(myLabel2, BorderLayout.SOUTH); //Create a file chooser final JFileChooser fc = new JFileChooser(); //In response to a button click: int returnVal = fc.showOpenDialog(panel1); frame.pack(); frame.setVisible(true); } }
| computing help | |