richiami di java input/output. import java.io.*; public class simple { public static void...

33
Richiami di Java Input/Output

Upload: maximilian-cooper

Post on 02-Jan-2016

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

Richiami di Java

Input/Output

Page 2: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

import java.io.*;public class Simple {

public static void main(String a[]){ new Simple(); }

public Simple() { byte buffer[]=new byte[100]; String s=null; System.out.println("Dammi una stringa"); try { int letti=System.in.read(buffer); s=new String(buffer,0,letti); } catch (IOException e) { e.printSTackTrace(); } System.out.println(s.length()+":"+s.indexOf('\n')+":"+s); }}

Raw IO from stdin,stdoutRaw IO from stdin,stdout

Page 3: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

import java.io.*;public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { BufferedReader is=new BufferedReader(

new InputStreamReader(System.in)); System.out.println("Dammi una stringa"); try { s=is.readLine(); } catch (IOException e) { e.printStackTrace();} System.out.println(s.length()+":"+s.indexOf('\n')+":"+s); }}

Simple IO from stdin,stdoutSimple IO from stdin,stdout

Page 4: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

import java.io.*;public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { BufferedReader is=new BufferedReader(new InputStreamReader(System.in)); int i=0; System.out.println("Dammi un int"); try { s=is.readLine(); } catch (IOException e) { e.printStackTrace();} try{ i=Integer.parseInt(s); } catch (NumberFormatException e) { System.out.println("Input non valido"); } System.out.println("Hai scritto "+i); }}

Reading an int from stdinReading an int from stdin

Page 5: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

package IO;import java.awt.*;import java.io.*;public class Application1 { public static void main(String[] args) { new Application1(); } public Application1() { Frame fr=new Frame(); FileDialog fd=new FileDialog(fr); fd.show(); String filename=fd.getFile(); String pathname=fd.getDirectory(); System.out.println(pathname+" "+filename); File file=new File(pathname,filename); try { FileWriter fw=new FileWriter(file); fw.write("Hello World"); fw.close(); } catch (IOException e) {} try {Thread.sleep(20000);} catch(Exception e){} }}

Page 6: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

To bring in information, a program opens a stream on an information source (a file, memory, a socket) and reads the information serially, like this:

StreamsStreams

Page 7: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

                                                                 

Similarly, a program can send information to an external destination by opening a stream to a destination and writing the information out serially, like this:

StreamsStreams

Page 8: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

No matter where the information is coming from or going to and no matter what type of data is

being read or written, the algorithms for reading and writing data is pretty much always the same.

Reading Writing

open a stream while more information

read information close the stream

open a stream while more information

write information close the stream

StreamsStreams

Page 9: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

The java.io  package contains a collection of stream classes that support these algorithms for reading and writing. These classes are divided into two class hierarchies based on the data type (either characters or bytes) on which they operate.

StreamsStreams

Page 10: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

However, it's often more convenient to group the classes based on their purpose rather than on the data type they read and write. Thus, we can cross-group the streams by whether they read from and write to data "sinks" or process the information as its being read or written.

Page 11: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

Reader and Writer are the abstract superclasses for character streams in java.io. Reader provides the API and partial implementation for readers--streams that read 16-bit characters--and Writer provides the API and partial implementation for writers--streams that write 16-bit characters.

Subclasses of Reader and Writer implement specialized streams and are divided into two categories: those that read from or write to data sinks (shown in gray in the following figures) and those that perform some sort of processing (shown in white).

Character StreamsCharacter Streams

Page 12: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

Character StreamsCharacter Streams

Page 13: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

Programs should use the byte streams, descendants of InputStream and OutputStream, to read and write 8-bit bytes. InputStream andOutputStream provide the API and some implementation for input streams (streams that read 8-bit bytes) and output streams (streams that write 8-bit bytes). These streams are typically used to read and write binary data such as images and sounds.

As with Reader and Writer, subclasses of InputStream and OutputStream provide specialized I/O that falls into two categories: data sink streams and processing streams.

Byte StreamsByte Streams

Page 14: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

Understanding the I/O Superclasses

Reader and InputStream define similar APIs but for different data types. For example, Reader contains these methods for reading characters and arrays of characters: int read() int read(char cbuf[]) int read(char cbuf[], int offset, int length)

InputStream defines the same methods but for reading bytes and arrays of bytes: int read() int read(byte cbuf[]) int read(byte cbuf[], int offset, int length)

Also, both Reader and InputStream provide methods for marking a location in the stream, skipping input, and resetting the current position.

IO superclasses - readingIO superclasses - reading

Page 15: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

Understanding the I/O Superclasses

Writer and OutputStream are similarly parallel. Writer defines these methods for writing characters and arrays of characters: int write(int c)int write(char cbuf[ ]) int write(char cbuf[ ], int offset, int length)

And OutputStream defines the same methods but for bytes: int write(int c) int write(byte cbuf[ ]) int write(byte cbuf[ ], int offset, int length)

All of the streams--readers, writers, input streams, and output streams--are automatically opened when created. You can close any stream explicitly by calling its close method. Or the garbage collector can implicitly close it, which occurs when the object is no longer referenced.

IO superclasses - writingIO superclasses - writing

Page 16: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

The Standard I/O Streams The concept of standard input and output streams is a C library concept that has been assimilated into the Java environment. There are three standard streams, all of which are managed by the java.lang.System class:

Standard input--referenced by System.in (instance of InputStream)

Used for program input, typically reads input entered by the user.

Standard output--referenced by System.out (instance of PrintStream)

Used for program output, typically displays information to the user.

Standard error--referenced by System.err (instance of PrintStream)

Used to display error messages to the user.

Standard IOStandard IO

Page 17: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

Sink Type Character Streams

Byte Streams

Memory CharArrayReader,CharArrayWriter

ByteArrayInputStream,ByteArrayOutputStream

StringReader,StringWriter

StringBufferInputStream

Pipe PipedReader,PipedWriter

PipedInputStream,PipedOutputStream

File FileReader,FileWriter

FileInputStream,FileOutputStream

Data sink streamsData sink streams

Page 18: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

Sink Type Character Streams

Byte Streams

Buffering BufferedReader,BufferedWriter

BufferedInputStream,BufferedOutputStream

Filtering FilterReader,FilterWriter

FilterInputStream,FilterOutputStream

Converting Bytes/Chars

InputStreamReader,OutputStreamWriter

Concatenation SequenceInputStream

Processing streamsProcessing streams

Page 19: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

Sink Type Character Streams

Byte Streams

Object Serialization

ObjectInputStream,ObjectOutputStream

Data Conversion

DataInputStream,DataOutputStream

Counting LineNumberReader

LineNumberInputStream

Peeking Ahead

PushbackReader PushbackInputStream

Printing PrintWriter PrintStream

Processing streamsProcessing streams

Page 20: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

File Represents a file on the native file system. You can create a File object for a file on the native file system and then query the object for information about that file (such as its full pathname).

FileDescriptor Represents a file handle (or descriptor) to an open file or an open socket. You will not typically use this class.

StreamTokenizer Breaks the contents of a stream into tokens. Tokens are the smallest unit recognized by a text-parsing algorithm (such as words, symbols, and so on). A StreamTokenizer object can be used to parse any text file. For example, you could use it to parse a Java source file into variable names, operators, and so on, or to parse an HTML file into HTML tags.

FilenameFilter Used by the list method in the File class to determine which files in a directory to list. The FilenameFilter accepts or rejects files based on their names. You could use FilenameFilter to implement simple regular expression style file search patterns such as foo*.

Classi accessorieClassi accessorie

Page 21: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

CheckedInputStream and CheckedOutputStream An input and output stream pair that maintains a checksum as the data is being read or written.

DeflaterOutputStreamand InflaterInputStream Compresses or uncompresses the data as it is being read or written.

GZIPInputStream and GZIPOutputStream Reads and writes compressed data in the GZIP format.

ZipInputStream and ZipOutputStream

Reads and writes compressed data in the ZIP format.

Classi accessorieClassi accessorie

Page 22: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

Esempio 1

Input/Output

Page 23: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

import java.io.*; public class Copy { public static void main(String[] args) throws IOException { File inputFile = new File(“originale.txt"); File outputFile = new File(“copia.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }}

Copy

Esempio: copy - 1Esempio: copy - 1

Page 24: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

Remember that FileReader and FileWriter read and write 16-bit characters. However, most native file systems are based on 8-bit bytes. These streams encode the characters as they operate according to the default character-encoding scheme.

You can find out the default character-encoding by using System.getProperty("file.encoding").

To specify an encoding other than the default, you should construct an OutputStreamWriter on a FileOutputStream and specify it.

Esempio: copy - 2Esempio: copy - 2

Page 25: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

public class CopyBytes { public static void main(String[] args) throws IOException{ File inputFile = new File(“originale.txt"); File outputFile = new File(“copia.txt"); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close() out.close(); }}

CopyBytes

Esempio: copy - 3Esempio: copy - 3

Page 26: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

Rhyming wordsWithout pipe streams, the program would have to store the results somewhere (such as in a file or in memory) between each step, as shown here:

With pipe streams, the output from one method could be piped into the next, as shown in this figure:

Rhyming words - 1Rhyming words - 1

Page 27: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

Esempio 2

Input/Output

Page 28: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

import java.io.*;public class RhymingWords { public static void main(String[] args) throws IOException { FileReader words = new FileReader("words.txt"); // do the reversing and sorting Reader rhymedWords = reverse(sort(reverse(words))); // write new list to standard out BufferedReader in = new BufferedReader(rhymedWords); String input; while ((input = in.readLine()) != null) System.out.println(input); in.close(); }

RhymingWords

Rhyming words - 2Rhyming words - 2

Page 29: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

public static Reader reverse(Reader source) throws IOException { BufferedReader in = new BufferedReader(source); PipedWriter pipeOut = new PipedWriter(); PipedReader pipeIn = new PipedReader(pipeOut); PrintWriter out = new PrintWriter(pipeOut); new ReverseThread(out, in).start(); return pipeIn; } public static Reader sort(Reader source) throws IOException { BufferedReader in = new BufferedReader(source); PipedWriter pipeOut = new PipedWriter(); PipedReader pipeIn = new PipedReader(pipeOut); PrintWriter out = new PrintWriter(pipeOut); new SortThread(out, in).start(); return pipeIn; }}

RhymingWords

Rhyming words - 3Rhyming words - 3

Page 30: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

import java.io.*;public class ReverseThread extends Thread { private PrintWriter out = null; private BufferedReader in = null; public ReverseThread(PrintWriter out, BufferedReader in) { this.out = out; this.in = in; }

ReverseThread

Rhyming words - 4Rhyming words - 4

Page 31: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

public void run() { if (out != null && in != null) { try { String input; while ((input = in.readLine()) != null) { out.println(reverseIt(input)); out.flush(); } out.close(); } catch (IOException e) { System.err.println("ReverseThread run: " + e); } } } Reverse

Thread

Rhyming words - 5Rhyming words - 5

Page 32: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

private String reverseIt(String source) { int i, len = source.length(); StringBuffer dest = new StringBuffer(len); for (i = (len - 1); i >= 0; i--) dest.append(source.charAt(i)); return dest.toString(); }}

ReverseThread

Rhyming words - 6Rhyming words - 6

Page 33: Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new

import java.io.*;public class SortThread extends Thread { private PrintWriter out = null; private BufferedReader in = null; public SortThread(PrintWriter out, BufferedReader in) { this.out = out; this.in = in; }

SortThread

Rhyming words - 7Rhyming words - 7