Reading From Files or URL - PowerPoint PPT Presentation

1 / 22
About This Presentation
Title:

Reading From Files or URL

Description:

Java libraries make it easy to read a file or resource on the network. ... Java apps can request images, sound files, data, or other resources from the ... – PowerPoint PPT presentation

Number of Views:81
Avg rating:3.0/5.0
Slides: 23
Provided by: Jim478
Category:
Tags: url | files | reading

less

Transcript and Presenter's Notes

Title: Reading From Files or URL


1
Reading From Files or URL
  • James Brucker

2
Input from Multiple Sources
  • Reading input from the console is not practical
    if you have a lot of data.
  • Java provides classes for reading from a File,
    from the network, or by communicating with
    another process.
  • Using Java Input Stream hierarchy, your program
    can read from any source without (much)
    modification.

InputStreamReader instr console or
FileInputStream or URL BufferedReader inbuf
new BufferedReader ( instr ) String s
inbuf.readLine( )
console
file
Web Server
3
Java Input Classes
Scanner - buffered reader and parser BufferedRead
er - input as a stream of lines
BufferedReader br new BufferedReader( isr )
InputStreamReader - input as a stream of chars
InputStreamReader isr new InputStreamReader(
InputStream )
InputStream - input as a stream of
bytes Subclasses FileInputStream PipedInputSt
ream FilterInputStream DataInputStream ...mo
re...
4
Reading From the Console
  • InputStreamReader (character at a time)

InputStreamReader isr new InputStreamReader(
System.in ) while ( isr.ready() ) int c
isr.read( ) // get a character process the
char
  • BufferedReader (char or line at a time)

InputStreamReader isr new InputStreamReader(
System.in ) BufferedReader input new
BufferedReader( isr ) // read a line and remove
surrounding spaces String s input.readLine(
).trim( ) // process the line, for
example String words s.split("\\s")
5
Reading From the Console
  • Scanner (line or token at a time)

Scanner console new Scanner( System.in ) while
( console.hasNext( ) ) String word
console.next( ) // next word int n
console.nextInt( ) // next integer double d
console.nextDouble() // next double String line
console.nextLine() // this line
  • change the token delimiter

console.useDelimiter("\\s,\\s") // comma
surrounded by zero or more spaces if (
console.hasNext("\\d10") ) // look for 10-digit
ID String id console.next("\\d10")
6
InputStream Hierarchy
  • A hierarchy of classes for processing input from
    different sources and types.
  • All classes can be used in any method expecting
    an InputStream.

Java InputStream Class Hierarachy InputStream Byt
eArrayInputStream FileInputStream PipedInputStre
am ObjectInputStream SequenceInputStream Filter
InputStream DataInputStream (binary) BufferedI
nputStream LineNumberInputStream PushbackInput
Stream
extend InputStream
extend FilterInputStream
7
Using Inheritance
  • The API for Scanner includes these constructors

Scanner( InputStream source ) Scanner( Readable
source ) Scanner( File source ) Scanner( String
source )
  • Since a FileInputStream is a subclass of
    InputStream, we can use it to create a Scanner

String filename "C/temp/sample.txt" FileInputS
tream fis new FileInputStream( filename
) Scanner input new Scanner( fis ) while (
input.hasNext( ) ) System.out.println(
input.nextLine( ) )
8
Using File Objects
  • Create a File object this does not create a new
    file on disk!

File infile new File("/some/path/sample.txt") F
ile infile2 new File("c\\stupid\\dos\\path\\sam
ple.txt")
  • Getting the File name and properties

String filename infile.getName( ) // or
infile.toString( ) String pathname
infile.getAbsolutePath() if ( ! infile.isfile(
) ) error( filename "is not a normal file"
) if ( infile.isDirectory( ) ) error( filename
" is a directory" ) if ( ! infile.exists( ) )
error( filename " does not exist" ) if ( !
infile.canRead( ) ) error( filename " cannot be
read." )
  • File object has many other useful methods! See
    Java API docs.

9
Opening a File as a FileInputStream
  • Create a File object, then connect to an
    InputStream

String filename "/path/sample.txt" File file
new File( filename ) if ( file.exists( ) )
FileInputStream fis new FileInputStream( file
) else System.err.println( filename " doesn't
exist")
  • Or, open FileInputStream directly from filename

FileInputStream fis new FileInputStream(
filename )
  • You can create a Scanner from either File or
    FileInputStream

Scanner filescan1 new Scanner( fis ) // use
FileInputStream Scanner filescan2 new Scanner(
file ) // use File
10
Reading a File using BufferedReader
  • Use the sequence
  • InputStream --gt InputStreamReader
    --gtBufferedReader

String filename "/path/sample.txt" FileInputStr
eam fis new FileInputStream( filename
) InputStreamReader reader new
InputStreamReader( fis ) BufferedReader input
new BufferedReader( reader )
  • Shortcut

BufferedReader input new BufferedReader( new
InputStreamReader( new FileInputStream(
filename ) ) )
  • Another way use a FileReader( ) extends
    InputStreamReader

BufferedReader input new BufferedReader( new
FileReader( filename ) )
11
Catching Exceptions
  • Does the file exist?
  • Do you have permission to read the file?
  • You must catch exceptions when opening a file.
    Most likely exceptions are
  • FileNotFoundException - file doesn't exist or
    you can't access it
  • NullPointerException - filename is a null string
  • SecurityException - usually in Applets, security
    manager violation

String filename "/some/path/sample.txt" try
Scanner input new Scanner( new
FileReader( filename) ) catch (
FileNotFoundException e ) / handle the error
/
12
Reading from a File
  • Since FileInputStream extends InputStream you can
    read from a file using same technique as reading
    System.in.
  • Example read data from a file using a Scanner.

String filename "/temp/sample.txt" Scanner
in try in new Scanner( new
FileInputStream( filename ) ) catch (
Exception e ) / handle the error / String
s try while ( in.hasNext( ) ) s
in.nextLine( ) process the input line
catch ( IOException e ) / handle I/O
exception /
13
Reading from the Network
  • Java libraries make it easy to read a file or
    resource on the network.
  • Easy to use network resource is URL (Uniform
    Resource Locator).
  • Examples of URLs are web page, file on an FTP
    server, local file, e-mail.

GET http//webserver/pathname/filename
open http//webserver
OK
GET pathname/filename
Web Server
Client
data from file
The client will cache the file (usually in a
temporary directory) until the process finishes
reading it.
14
Uniform Resource Locators (URL)
  • Java apps can request images, sound files, data,
    or other resources from the server using Uniform
    Resource Locators (URL) to identity the resource.
  • What is the structure of a URL?
  • http//www.cpe.ku.ac.th/jim/dictionary.txt

Protocol http ftp
Hostname or IP address
Path and resource name, the path is optional
Relative URLs in web pages (HTML) it is
possible to omit the hostname and path if they
are the same as the host and path from which the
web page was loaded. E.g. ltimg srclogo.jpggt if
the file is in the same directory has the
requesting file. In Java applets, you generally
need to specify a full URL.
15
Opening a URL
  • Create a URL object, then connect to an
    InputStream, ...

String urlname "http//www.cpe.ku.ac.th/jim/sa
mple.txt" URL url new URL( urlname
) InputStream instream url.openStream( ) //
connect BufferedReader or Scanner to the
input BufferedReader input new BufferedReader(
new InputStreamReader( instream ) )
  • URL class is java.net.URL. So, at top of your
    program import

import java.net.URL
  • or specify the path in your Java source

java.net.URL url new java.net.URL( urlname )
16
Catching URL Exceptions
  • You must handle exceptions when opening a URL.
  • Most likely exception MalformedURLException

String urlname "http//www.cpe.ku.ac.th/jim/sa
mple.txt" try URL url new URL( urlname
) InputStream instream url.openStream( ) //
now connect a Scanner to the input
stream Scanner input new Scanner( instream )
catch ( MalformedURLException e )
System.out.println("Couldn't open
"urlname) System.out.println( e.toString() )
What is wrong with the statement to create a
Scanner object?
17
Reading from a URL
  • Open an InputStreamReader or BufferedReader
    (previous slide)
  • Get input same as from console or file

String urlname "http//www.cpe.ku.ac.th/jim/s
ample.txt" Scanner input // must define
outside of "try" block try URL url new URL(
urlname ) input new Scanner( url.openStream(
) ) catch ( MalformedURLException e ) /
handle error / // Read input data same as from
console try while( input.hasNext( ) )
String s input.nextLine( ) process the
input line catch( IOException e )
System.err.println("Error "e)
18
Reading from Anywhere
  • You can write general code to read from a URL,
    file, or console...

/ Create an InputStream for reading a file or
URL / InputStream getInputStream( String
filename ) // TO DO must add try ...
catch for Exceptions InputStream instream if (
filename null filename.equals("") ) /
use console / instream System.in else if
( filename.indexOf("//") gt 0 ) / filename is
a URL / instream new URL(filename).openStream
( ) else / open as a local file / instream
new FileInputStream( filename ) return
instream
19
Handling Exceptions
  • You should catch common errors and return a null
    stream

/ Create an InputStream for reading a file or
URL / InputStream getInputStream( String
filename ) try ... catch
(MalformedURLException e) err.println("Invalid
URL, fumble fingers.\n"e) instream
null catch (IOException e) err.println("So
rry, IOException opening " filename"\n"e)
instream null return instream
20
Printing Exception Details
  • The error handler (catch block) prints the
    exception object. This invokes the exception's
    toString() method that prints a detailed message.

try ... catch (IOException e)
err.println("Oops! I/O Error.\n"
e) instream null
same as writing e.toString()
Exercise generate an I/O exception (try to read
a non-existent file) and look at the message
printed by e.toString().
21
Printing an Exception Stack Trace
  • Exception has a method printStackTrace() that
    prints a detailed call stack trace, useful for
    debugging (but frightening to casual users).
    Invoked as a statement, not an argument to
    println( ).

try ... catch (IOException e)
e.printStackTrace()
java.io.FileNotFoundException bogusfile.txt (The
system cannot find the file specified) at
java.io.FileInputStream.open(Native Method) at
java.io.FileInputStream.ltinitgt(Unknown
Source) at MyClass.getInputStream(MyClass.java8)
at MyTester.main(MyTester.java28)
22
For More Information
Sun Java Tutorials (online) I/O Reading and
Writing http//java.sun.com/docs/books/tutorial/es
sential/io/ Handling Errors with
Exceptions http//java.sun.com/docs/books/tutorial
/essential/exceptions/ Sample Program to Read
from Anywhere http//www.cpe.ku.ac.th/jim/java/ex
amples/ReadFromAnywhere.java Beginner's Guide To
URLs http//archive.ncsa.uiuc.edu/SDG/Software/Mos
aic/Demo/url-primer.html (short document)
Write a Comment
User Comments (0)
About PowerShow.com