Download CSci 161

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CSci 161
Input and Output with Java
CSci 161
1
Command Line Arguments
public static void main (String [ ] args) {
// check args.length
// access args[0], args[1], etc if they exist
// arguments are strings (“input.txt”, “1234”, etc.)
// methods like Integer.parseInt(...) are handy
}
CSci 161
2
Standard I/O Streams
stdin
System.in is an InputStream (connected to
keyboard unless redirected) ... “handle” is 0
stdout
System.out is a PrintStream (connected to console
unless redirected) ... “handle” is 1
stderr
System.err is a PrintStream (connected to console
unless redirected) ... “handle” is 2
CSci 161
3
Keyboard Input
System.in is an InputStream object
it is open when your program begins execution
it has a read() method (reads bytes)
InputStreamReader object
reads bytes, translates into characters
it has a read() method (reads characters)
BufferedReader object
has a readLine() method that returns a String
detects end-of-line (so you don't have to)
CSci 161
4
Console Output
System.out and System.err are PrintStreams
a PrintStream never throws an I/O exception (that's
nice)
some methods can throw “null pointer exceptions” or
“index out of bounds exceptions” though
A PrintStream is only used for outputting characters
every object has a toString() method that creates a
character representation of it
primitive types have the same character string
representations as their wrapper class equivalents
CSci 161
5
The JOptionPane class
import this class from javax.swing
showMessageDialog(...) method can be used in
place of console output
showInputDialog(...) method can be used in
place of keyboard input
these methods never throw I/O exceptions
CSci 161
6
Homework Exercise
Send a “Hello, World!” message to the console
via the System.out PrintStream
Do it again using the System.err PrintStream
Do it again using JOptionPane's
showMessageDialog(...) method
CSci 161
7
File Input and Output
Create a FileInputStream object in order to read
from a local file
FileInputStream in = new FileInputStream(“myfile.xyz”);
read() method ... reads bytes
Create a FileOutputStream object in order to
write to a local file
FileOutputStream in = new FileOutputStream(“myoutput.xyz”);
write() method ... writes bytes
I/O Exceptions may be thrown by the methods of
these objects
CSci 161
8
Text Files
text file input
reading bytes is a
pain
create an
InputStreamReader
object to bridge
between bytes and
characters
create a
BufferedReader so
you can read an entire
line at at time
CSci 161
text file output
writing bytes is a pain
create a PrintStream
object and use its
print(..) and println(..)
methods
no I/O exceptions
from a PrintStream
closing the file when
you're done is always
a good idea
9
Homework Exercise
Read a text file and echo its contents to the
console.
CSci 161
10
Binary Files
binary file input
binary file output
reading bytes is a
pain
writing bytes is a pain
create a
DataOutputStream
object
create a
DataInputStream
object to bridge
between bytes and
primitive types
methods are readInt(),
readDouble(),
etc.“watch” for EOF
CSci 161
methods are
writeInt(), writeFloat(),
etc.
close the file when
you're done
11
Homework Exercise
Write a Java program to create a new binary file
containing the integer values 1, 2, 3, 4, 5, 6, 7, 8,
9 and 10.
Write a java program to read the contents of the
file created above. What happens if you try to
read the values as short (16-bit) integer values?
CSci 161
12
Reading and Writing Objects
Inputting objects
Outputting objects
connect an
ObjectInputStream to
your input stream
connect an
ObjectOutputStream
to your output stream
use the readObject(..)
method
use the writeObject(..)
method
“watch” for EOF
outputted objects
must be Serializable
use casts to “tell” Java
what type of object
you have read (or
expect to have read)
CSci 161
close the file when
you're done
13
Homework Exercise
Create a Java Vector<Integer> containing
Integers with the values 1 through 10. Write the
Vector (as a single object) to an object output file.
Write another Java program to read this object file
and print the contents of the Vector. Are all ten of
these numbers still in the inputted Vector?
CSci 161
14
Accessing Remote Files
import the URL class from the java.net package
create an instance of this class
URL myurl = new URL(“http://und.edu/applynow.html”);
a URL object has an openstream() method
it opens a connection to the URL and returns an
InputStream for reading from that connection
work with this InputStream just as you would
with any other InputStream (does the URL
identify a text file? a binary file? an object file?)
CSci 161
15
Homework Exercise
Read your favorite html page (a text file). Display
the contents of the html file on your console.
CSci 161
16
Scanners
a Scanner is a handy tool for finding the
individual pieces of a chunk of text (from an
input file, a String, or somewhere else)
default delimiters are white space characters
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong()
}
CSci 161
17
StreamTokenizer
A StreamTokenizer can be used to find, in
order, the “tokens” in an input character stream
the nextToken() method fetches the next token
from the stream
it might be a number, it might be a word
check a flag to see which, or to see if EOF was
detected, and proceed appropriately
The Scanner class (since Java 1.5) seems to
make this class (since Java 1.0) unnecessary
CSci 161
18
Things to Remember
Read the Java API for details about the classes
and methods you want to use for I/O
note the package name, so you can import correctly
what I/O exceptions are thrown by the methods you
intend to use? Should you handle them or throw
them ... you must do one or the other.
how is EOF indicated?
a special return value?
the throwing of an EOFException? (which you MUST
handle)
CSci 161
19