Download Basic I/O - U

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
Basic I/O
Alexandre Bergel
[email protected]
09/06/2010
This class covers the Java platform classes used
for basic Input/Output (I/O)
http://java.sun.com/docs/books/tutorial/essential/io/index.html
I/O Streams
An I/O Stream represents an input source or an
output destination
A stream can represent a disk file, device, memory
array...
Streams support many different kinds of data (simple
bytes, primitive data types, localized characters,
objects)
Reading information into a program
Writing information from a program
Byte Streams
Programs use byte streams to perform input and
output of 8-bit bytes
All byte stream classes are descended from
InputStream and OutputStream
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Comments & Advices on Byte
Streams
Notice that read() returns an int value
If the input is a stream of bytes, why doesn't read()
return a byte value?
To use -1 to indicate that it has reached the end of
the stream
Closing a stream when it's no longer needed is very
important
This practice helps avoid serious resource leaks
Comments & Advices on Byte
Streams
CopyBytes seems like a normal program, but it
actually represents a kind of low-level I/O that you
should avoid
Byte streams should only be used for the most
primitive I/O
So why talk about byte streams? Because all other
stream types are built on byte streams
Character Streams
The Java platform stores character values using
Unicode conventions
Unicode is a standard for a consistent representation
of text expressed in most of the world’s writing
systems
Contains more than 107 000 characters
Character Streams
All character stream classes are descended from
Reader and Writer
As with byte streams, there are character stream
classes that specialize in file I/O: FileReader and
FileWriter
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyCharacters {
public static void main(String[] args) throws IOException {
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader("xanadu.txt");
outputStream = new FileWriter("characteroutput.txt");
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
CopyCharacters vs CopyBytes
The most important difference is that CopyCharacters
uses FileReader and FileWriter for input and output in
place of FileInputStream and FileOutputStream
Notice that both CopyBytes and CopyCharacters use
an int variable to read to and write from
However, in CopyCharacters, the int variable holds a
character value in its last 16 bits
In CopyBytes, the int variable holds a byte value in its
last 8 bits
Character Streams that Use Byte
Streams
Character streams are often "wrappers" for byte
streams
The character stream uses the byte stream to
perform the physical I/O, while the character stream
handles translation between characters and bytes
FileReader uses FileInputStream
FileWriter uses FileOutputStream
Line-Oriented I/O
Text files are usually structured as lines
a string of characters with a line terminator at the end
A line terminator can be a carriage-return/line-feed sequence
("\r\n"), a single carriage-return ("\r"), or a single line-feed ("\n")
The CopyLines example invokes
BufferedReader.readLine and PrintWriter.println to do
input and output one line at a time
import
import
import
import
import
java.io.FileReader;
java.io.FileWriter;
java.io.BufferedReader;
java.io.PrintWriter;
java.io.IOException;
public class CopyLines {
public static void main(String[] args) throws IOException {
BufferedReader inputStream = null;
PrintWriter outputStream = null;
try {
inputStream =
new BufferedReader(new FileReader("xanadu.txt"));
outputStream =
new PrintWriter(new FileWriter("characteroutput.txt"));
String l;
while ((l = inputStream.readLine()) != null) {
outputStream.println(l);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}}}
Buffered Streams
Most of the examples we've seen so far use
unbuffered I/O
This means each read or write request is handled
directly by the underlying OS
This can make a program much less efficient when
using networks, frequent access disk,...
Buffered Streams
To reduce this kind of overhead, the Java platform
implements buffered I/O streams
Buffered input streams read data from a memory area
known as a buffer; the native input API is called only
when the buffer is empty
Similar schema for buffered output streams
An unbuffered stream may be converted into a
buffered stream using wrappers
...
inputStream =
new BufferedReader(new FileReader("xanadu.txt"));
outputStream =
new BufferedWriter(new FileWriter("characteroutput.txt"));
...
Epilogue: XML manipulation
XML is designed to transport and store data
XML stands for eXtensible Markup Language
XML is a markup language much like HTML
XML is designed to carry data
Can be used to define a load/save function in your
application
Simple Example
<notes>
<note>
<to>students</to>
<from>cc3002</from>
<heading>Reminder</heading>
<body>Don't forget the control this Friday!</
body>
</note>
<note>
<to>students</to>
<from>cc3002</from>
<heading>Chile and the Mundial?</heading>
<body>Hip hip Chile!</body>
</note>
</notes>
package cc3002;
import java.io.FileInputStream;
import java.io.InputStream;
import
import
import
import
javax.xml.stream.XMLEventReader;
javax.xml.stream.XMLInputFactory;
javax.xml.stream.XMLStreamException;
javax.xml.stream.events.XMLEvent;
public class XMLExample {
public static void main(String[] argv) {
try {
// First create a new XMLInputFactory
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
InputStream in = new FileInputStream("test.xml");
XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
if (event.isStartElement() && event.toString().equals("<from>"))
readFROMTag(eventReader);
if (event.isStartElement() && event.toString().equals("<body>"))
readBodyTag(eventReader);
}
}
catch (Exception e) { }
}...
private static void readFROMTag(XMLEventReader eventReader) throws
XMLStreamException {
XMLEvent event = eventReader.nextEvent();
System.out.println("Message from: " + event.toString());
}
private static void readBodyTag(XMLEventReader eventReader) throws
XMLStreamException {
XMLEvent event = eventReader.nextEvent();
System.out.println("Message content: " + event.toString());
}
}
Message
Message
Message
Message
from: cc3002
content: Don't forget the control this Friday!
from: cc3002
content: Hip hip Chile!
License
http://creativecommons.org/licenses/by-sa/2.5
Attribution-ShareAlike 2.5
You are free:
• to copy, distribute, display, and perform the work
• to make derivative works
• to make commercial use of the work
Under the following conditions:
Attribution. You must attribute the work in the manner specified by the author or licensor.
!
Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting
work only under a license identical to this one.
• For any reuse or distribution, you must make clear to others the license terms of this work.
• Any of these conditions can be waived if you get permission from the copyright holder.
Your fair use and other rights are in no way affected by the above.