Java: grafica, applets e pagine web

Download Report

Transcript Java: grafica, applets e pagine web

Richiami di Java
Input/Output
Raw IO from stdin,stdout
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);
}
}
Simple IO from stdin,stdout
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);
}
}
Reading an int from stdin
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);
}
}
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){}
}
}
Streams
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:
Streams
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:
Streams
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
Streams
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.
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.
Character Streams
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 Streams
Byte Streams
Programs should use the byte streams,
descendants of InputStream and
OutputStream, to read and write
8-bit bytes. InputStream and
OutputStream 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.
IO superclasses - reading
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 - writing
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.
Standard IO
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.
Data sink streams
Sink Type Character
Streams
Byte Streams
Memory
CharArrayReader,
CharArrayWriter
ByteArrayInputStream,
ByteArrayOutputStream
StringReader,
StringWriter
StringBufferInputStream
Pipe
PipedReader,
PipedWriter
PipedInputStream,
PipedOutputStream
File
FileReader,
FileWriter
FileInputStream,
FileOutputStream
Processing streams
Sink Type
Character
Streams
Byte Streams
Buffering
BufferedReader,
BufferedWriter
BufferedInputStream,
BufferedOutputStream
Filtering
FilterReader,
FilterWriter
FilterInputStream,
FilterOutputStream
Converting
Bytes/Chars
InputStreamReader,
OutputStreamWriter
Concatenation
SequenceInputStream
Processing streams
Sink Type
Character
Streams
Byte Streams
Object
Serialization
ObjectInputStream,
ObjectOutputStream
Data
Conversion
DataInputStream,
DataOutputStream
Counting
LineNumberReader
Peeking Ahead PushbackReader
Printing
PrintWriter
LineNumberInputStream
PushbackInputStream
PrintStream
Classi accessorie
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 accessorie
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.
Esempio 1
Input/Output
Esempio: copy - 1
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();
}
}
Esempio: copy - 2
Remember that FileReader and FileWriter read and write 16bit characters. However, most native file systems are based on 8bit 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 - 3
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();
}
}
Rhyming words - 1
Rhyming words
Without 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:
Esempio 2
Input/Output
Rhyming words - 2
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();
}
Rhyming words - 3
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;
}
}
Rhyming words - 4
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;
}
Rhyming words - 5
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);
}
}
}
Rhyming words - 6
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();
}
}
Rhyming words - 7
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;
}