Download File

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
Introduction to Programming
G50PRO
University of Nottingham
Unit 11 : Files Input/Ouput
Paul Tennent
http://paultennent.wordpress.com/G50PRO.html
[email protected]
Room C7
Overview








2
Java I/O
UserInput Class Demo
Exceptions Intro
try, catch, and finally blocks
Exceptions Example
Files I/O
File Examples
Extra Reading
http://www.cs.nott.ac.uk/~eoe
Java I/O

Input/output operations direct data from the keyboard, files or
programs into your program and from there to the screen,
printer, files or other programs.

Java uses the concept of streams to manage this flow of data.

System.in and System.out objects read and write from the
standard input and output streams.

Java also uses file streams, data streams, pipe streams and
object streams to manipulate I/O.
For these streams you must access the io class library using:

3
import java.io.*
http://www.cs.nott.ac.uk/~eoe
UserInput Class Demo
// readChar Method
public static char readChar() {
char returnValue = 'a';
DataInputStream dis = new DataInputStream(System.in);
try {
String userInput = new String(dis.readLine());
//return just the first character
returnValue = userInput.charAt(0);
} catch(Exception e) {
System.out.println("Exception while reading user's
input as a char");
}
return returnValue;
} // end readChar()
4
http://www.cs.nott.ac.uk/~eoe
Exceptions Intro

The Java programming language uses exceptions to enable the
developer to handle errors or exceptional events

The term exception is shorthand for the phrase "exceptional event."

An exception is an event that occurs during the execution of a
program that disrupts the normal flow of instructions

5
try, catch, and finally blocks are used to write an exception handler
http://www.cs.nott.ac.uk/~eoe
try, catch, and finally blocks

enclose the code that might throw an exception within a try block

provide one or more catch blocks directly after the try block to
deal with different expected exceptions

Each catch block is an exception handler and handles the type of
exception indicated by its argument

The finally block always executes when the try block exits. This
ensures that the finally block is executed even if an unexpected
exception occurs – usually used for cleanup code
6
http://www.cs.nott.ac.uk/~eoe
Exceptions Example :
public static void main (String[] args){
int[] ar = new int[10];
try {
//trying to write to the 10th element of the array
ar[10] = 0;
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Caught "
+ "ArrayIndexOutOfBoundsException: "
+
e.getMessage());
} finally {
System.out.println("finally block executed");
}
}//end main
7
http://www.cs.nott.ac.uk/~eoe
Files I/O
Access file properties by creating a file handle
using File class



Use file streams which are primitive streams
whose sources or destinations are files.



8
File myFile = new File(“data.txt");
// name in current dir
A file handle can be used d by various file class methods
to access the properties of a specific file
Byte based streams [8-bit]
FileInputStream and FileOutputStream
Character based streams [16-bit]
FileReader and FileWriter
http://www.cs.nott.ac.uk/~eoe
Example : Read File
public static void main( String[] args ) {
try{
int n;
FileInputStream fis = new FileInputStream("data1.csv");
while ( ( n = fis.available() ) > 0 ) {
byte[] b = new byte[ n ];
int result = fis.read( b );
if ( result != -1 ){
String s = new String( b );
System.out.print( s );
}
} // end while
} catch ( IOException e ) {
System.err.println( "Error: " + e.getMessage() ); }
}9 // end main
http://www.cs.nott.ac.uk/~eoe
Example : Create empty File
public static void main( String[] args ) {
Path file = “data.txt”;
try {
file.createFile();
//Create the empty file with default permissions, etc.
} catch (FileAlreadyExists x) {
System.err.println("file named already exists”);
} catch (IOException x) {
//Some other sort of failure, such as permissions.
System.err.println(“Error:” + x.getMessage());
}
} // end main
10
http://www.cs.nott.ac.uk/~eoe
Example : Write to File
public static void main( String[] args ) {
FileOutputStream fos;
try{
fos = new FileOutputStream( "data.txt" );
String s = "Test write to file ";
byte data[] = s.getBytes();
fos.write( data );
} catch ( IOException e ) {
System.err.println( e.getMessage() );
}
} //end main
11
http://www.cs.nott.ac.uk/~eoe
Extra Reading

12
http://java.sun.com/docs/books/tutorial/essent
ial/io/file.html
http://www.cs.nott.ac.uk/~eoe
Summary








13
Java I/O
UserInput Class Demo
Exceptions Intro
try, catch, and finally blocks
Exceptions Example
Files I/O
File Examples
Extra Reading
http://www.cs.nott.ac.uk/~eoe