Exceptions enable you to write the main flow of your code and to deal with the exceptional cases elsewhere.
Exceptions is the ability to propagate error reporting up the call stack of methods (throws clause).
With exception chaining, an exception can point to the exception that caused it, which can in turn point to the exception that caused it, and so on (stack trace).
Checked exception: application should anticipate and recover eg: java.io.FileNotFoundException
Unchecked Exception are indicated by Error, RuntimeException, and their subclasses.
Error are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. eg: java.io.IOError (unable to read the file because of a hardware or system malfunction)
Runtime exception are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. eg: NullPointerException
The finally block always executes when the try block exits (after catch).
If there is return statement in finally and try; finally block return is executed.
The Throwable class is the superclass of all errors and exceptions in the Java language.
Throwable getCause()
Throwable initCause(Throwable)
Throwable(String, Throwable)
Throwable(Throwable)
getCause returns the exception that caused the current exception, and initCause returns the current exception.
From Java 5 we have logging mechanism available in jdk
java.util.logging.*;
Handler handler = new FileHandler("OutFile.log");
Logger logger = Logger.getLogger("test");
logger.addHandler(handler);
StackTraceElement elements[] = e.getStackTrace();
for (int i = 0, n = elements.length; i < n; i++) {
logger.log(Level.WARNING, elements[i].getMethodName());
}
-----------------------IO Streams-------------------------
The sequential access streams can be divided into two groups: those that read and write bytes and those that read and write Unicode characters.
Programs use byte streams to perform input and output of 8-bit bytes.
All byte stream classes are descended from InputStream and OutputStream. (abstract)
java.io.FileInputStream in = new FileInputStream("a.txt");
while ((c = in.read()) != -1) { //return value of read is int, the int variable holds a byte value in its last 8 bits
Using a int as a return type allows read() to use -1 to indicate that it has reached the end of the stream.
All other stream types are built on byte streams (only be used for the most primitive I/O).
The Java platform stores character values using Unicode conventions. Character stream I/O automatically translates this internal format to and from the local character set. In Western locales, the local character set is usually an 8-bit superset of ASCII.
A program that uses character streams in place of byte streams automatically adapts to the local character set and is ready for internationalization — all without extra effort by the programmer.
All character stream classes are descended from Reader and Writer (abstract)
FileReader inputStream = new FileReader("a.txt");
FileWriter outputStream = new FileWriter("b.txt");
while ((c = inputStream.read()) != -1) { //return value of read is int, the int variable holds a character value in its last 16 bits;
outputStream.write(c);
There are two general-purpose byte-to-character "bridge" streams: InputStreamReader and OutputStreamWriter.
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.
Character I/O usually occurs in bigger units than single characters. One common unit is the line: 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").
To do this use BufferedReader and PrintWriter.
BufferedReader inputStream = new BufferedReader(new FileReader("a.txt"));
PrintWriter outputStream = new PrintWriter(new FileWriter("b.txt"));
while ((l = inputStream.readLine()) != null) {
unbuffered I/O means each read or write request is handled directly by the underlying OS.
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.Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.
There are four buffered stream classes used to wrap unbuffered streams: BufferedInputStream and BufferedOutputStream create buffered byte streams, while BufferedReader and BufferedWriter create buffered character streams.
It often makes sense to write out a buffer at critical points, without waiting for it to fill. This is known as flushing the buffer.
Objects of type Scanner are useful for breaking down formatted input into tokens and translating individual tokens according to their data type. By default, a scanner uses white space to separate tokens.
java.util.Scanner sc = new Scanner(new File("io.txt"));
s.useDelimiter(",\\s*");
Stream objects that implement formatting are instances of either PrintWriter, a character stream class, and PrintStream, a byte stream class.
int i = 2; double r = Math.sqrt(i);
System.out.format("The square root of %d is %f.%n", i, r); //output The square root of 2 is 1.414214.
- d formats an integer value as a decimal value.
- f formats a floating point value as a decimal value.
- n outputs a platform-specific line terminator.
- x formats an integer as a hexadecimal value.
- s formats any value as a string.
- tB formats an integer as a locale-specific month name.
Don't use \n unless you specifically want a linefeed character. To get the correct line separator for the local platform, use %n.
In addition to the conversion, a format specifier can contain several additional elements that further customize the formatted output.
System.out.format("%f, %1$+020.10f %n", Math.PI);
//Output 3.141593, +00000003.1415926536

Command line interaction in two ways: through the Standard Streams and through the Console.
Three Standard Streams: Standard Input, accessed through System.in; Standard Output, accessed through System.out; and Standard Error, accessed through System.err.
You might expect the Standard Streams to be character streams, but, for historical reasons, they are byte streams
To use Standard Input as a character stream, wrap System.in in InputStreamReader.
InputStreamReader cin = new InputStreamReader(System.in);
A more advanced alternative to the Standard Streams is the Console. Methods to access the character-based console device, if any, associated with the current Java virtual machine.
Before a program can use the Console, it must attempt to retrieve the Console object by invoking System.console(). If the Console object is available, this method returns it. If System.console returns NULL, then Console operations are not permitted, either because the OS doesn't support them or because the program was launched in a noninteractive environment.
The Console object supports secure password entry through its readPassword method. This method helps secure password entry in two ways. First, it suppresses echoing, so the password is not visible on the user's screen. Second, readPassword returns a character array, not a String, so the password can be overwritten, removing it from memory as soon as it is no longer needed.
Console c = System.console();
String login = c.readLine("Enter your login: ");
char [] newPassword1 = c.readPassword("Enter your new password: ");
Read and write operations are synchronized to guarantee the atomic completion of critical operations; therefore invoking methods readLine(), readPassword(), format(), printf() as well as the read, format and write operations on the objects returned by reader() and writer() may block in multithreaded scenarios.
Data streams support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as well as String values. All data streams implement either the DataInput interface or the DataOutput interface. This section focuses on the most widely-used implementations of these interfaces, DataInputStream and DataOutputStream.
out = new DataOutputStream(byte OutputStream);
in = new DataInputStream(byte InputStream);
The writeUTF method writes out String values in a modified form of UTF-8.

Object streams support I/O of objects.
The object stream classes are ObjectInputStream and ObjectOutputStream. These classes implement ObjectInput and ObjectOutput, which are subinterfaces of DataInput and DataOutput.
If readObject is to reconstitute an object from a stream, it has to be able to reconstitute all of the objects the original object referred to. These additional objects might have their own references, and so on. In this situation, writeObject traverses the entire web of object references and writes all objects in that web onto the stream. Thus a single invocation of writeObject can cause a large number of objects to be written to the stream.
A stream can only contain one copy of an object, though it can contain any number of references to it. Thus if you explicitly write an object to a stream twice, you're really writing only the reference twice. If a single object is written to two different streams, it is effectively duplicated — a single program reading both streams back will see two distinct objects.
File is a class that helps you write platform-independent code that examines and manipulates files and directories.
Random access files support nonsequential access to disk file data.
File.separator to specify the file name in a platform-independent way.
File a = new File("xanadu.txt");
a.getParent(); //returns NULL
File b = new File(".." + File.separator + "examples" + File.separator + "xanadu.txt");
b.getParent(); //returns ..\examples
File.compareTo()would not consider a and b to be the same. Even though they refer to the same file, the names used to construct them are different.
The delete method deletes the file immediately, while the deleteOnExit method deletes the file when the virtual machine terminates.
The setLastModified sets the modification date/time for the file.
new File("xanadu.txt").setLastModified(new Date().getTime());
The renameTo() method renames the file. The file name string behind the File object remains unchanged, so the File object will not refer to the renamed file.
The mkdir method creates a directory. The mkdirs method does the same thing, after first creating any parent directories that don't yet exist.
The list method returns an array of String file names, while listFiles returns an array of File objects.
File Static Methods:
The createTempFile method creates a new file with a unique name and returns a File object referring to it
The listRoots returns a list of file system root names.eg: windows-a:\,c:\ and unix-\
Random access files permit nonsequential, or random, access to a file's contents.
The java.io.RandomAccessFile class implements both the DataInput and DataOutput interfaces and therefore can be used for both reading and writing.
creates a RandomAccessFile to read the file named xanadu.txt:
new RandomAccessFile("xanadu.txt", "r");
new RandomAccessFile("xanadu.txt", "rw"); //for read write
RandomAccessFile supports the notion of a file pointer. The file pointer indicates the current location in the file. When the file is first created, the file pointer is set to 0, indicating the beginning of the file. Calls to the read and write methods adjust the file pointer by the number of bytes read or written.
RandomAccessFile contains three methods for explicitly manipulating the file pointer.
int skipBytes(int) — Moves the file pointer forward the specified number of bytes
void seek(long) — Positions the file pointer just before the specified byte
long getFilePointer() — Returns the current byte location of the file pointer
FileWriter writer = new FileWriter (String filename, boolean append);
//to append data to eof Alternative ...
RandomAccessFile file = new RandomAccessFile(datafile, "rw");
file.skipBytes((int)file.length()); //skip to the end of the file
file.writeBytes("Add this text to the end of datafile"); //write at the end of the file
file.close();
No comments:
Post a Comment