** I/O, Applets and Other Topics**
- It introduces the two Java important package
- I/O package support Java I/O stream and also input/output file.
- Applet package supports with the applet.
- These chapter examine the try statement of java important things as Transient,Volatile,Strictfp,instanceof,native and assert.
I/O(input/output):
- I/O are graphical oriented as java GUI (graphical user interface) frameworks such as Swing,Awt, or JavaFX for user interaction such as web applications.
Console I/O is limited and somewhat awkward to use in simple programs.
Text based I/O is not used in real world java programming.
Java input and output system is cohesive and consistent.
Streams:
- Java perform programs through streams.A stream is abstraction that either produces or consumes the information.
- A stream is a physical device by java I/O system.
- Streams are a clean way to deal with input/ output without having every part of your code understand the difference between a keyboard and a network.
Byte streams and Character Streams:
- Byte streams provide easy to handle input and output by using byte.It used for reading and writing binary data.
- character streams provide easy to handle I/O characters.It used for unicode.
- In original version java1.0 only byte is used.
- In later java1.1 character is introduced.however, the some classes and methods were deprecated.
Byte stream Classes:
- Byte stream defined two class hierarchy such as two abstract classes as Inputstream and outputstream .
Each of the abstract class have the several concrete subclasses that handles the different among the various devices such as disk disk,network and memory buffers.
**Streamclass --> Meaning**
Buffered Inputstream --> bufferd input streamS
Buffered Outputstream --> bufferd Output stream
ByteArrayInputStream --> Input stream that reads from a byte array
ByteArrayOutputStream --> Output stream that writes to a byte array
PipedInputStream --> Input pipe
PipedOutputStream --> Output pipe
PrintStream --> Output stream that contains print() and println().
Character Stream classes:
**Stream class --> Meaning**
BufferedReader ---> Buffered input character stream
BufferedWriter --> Buffered output character stream
CharArrayReader --> Input stream that reads from a character array
CharArrayWriter --> Output stream that writes to a character array
- The two of the most important methods are read() and write() which read and write the characters of data.
- Each has a form that is abstract and must be overridden by derived stream classes.
Predefined streams:
- System contains the predefined variables as stream variables as in,out and err.
- This field defined as static,final and public.
- System.out refers to the standard output system
- System.in refers to the standard input.
- System.err refers to the standard error system.
- System.in is an object of type Inputstream
- System.out and System.err is an object of type Printstream.
Reading Console Input:
- The preferred method of reading console input is to use a character-oriented stream.
- This makes your program easier to internationalize and maintain.
- Console input is accomplished by reading from System.in.
To obtain a character based stream that is attached to the console, wrap System.in in a BufferedReader object.
BufferedReader supports a buffered input stream.
A commonly used constructor is shown as,
BufferedReader(Reader inputReader)
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
After this statement executes, br is a character-based stream that is linked to the console through System.in.
Reading Characters:
- To read a character from a bufferedReader use read().
Each time a read() is called it reads a character from input stream and return it as integer value.It return -1 when the end of the stream is encountered.It can throw input output(IO)exception.
It uses a specific word "q" then it quit to terminate the method and simply thrown out of the main().
Reading Strings:
- To read a string from the keyboard use the version of redline() in the member of bufferedReader class.
- It read the bufferedReader class from the console.
Example:
class BRReadLines {
public static void main(String args[]) throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("stop"));
}
}
It uses a specific word "stop" then it quit to terminate the method and simply thrown out of the main().
- br is a character-based stream that linked to the console through system.in.
Writing Console output:
- It is easily accomplished with the print() and println().It defined by the ClassPrintStream.
- Eventhough a system.out is a byte stream used it for simple program output is still acceptable.
- It implements a low level method write().
- Void write (int byteval)
- This method writes the byte specified by byteval.byteval is declared as integer a low order eight bits are assigned.
PrintWriter class:
- Printwriter is one of the character based classes.It defines the several constructors.
- Printwriter (OutputStream outputstream ,_Boolean _flushingOn)
- PrintWriter support the print() and println() methods.
- To write the console by using a PrintWriter,specify the System.out for the output stream and flushing.
Reading and Writing Files:
- Java provides a number of classes that allow you to read and write files.it is important to understand that file I/O is quite large.
- Two of the most often stream classes are fileInputStream and fileOutputStream.which create byte stream linked to files.
- Although both classes support additional constructors.
The some forms are,
FileInputStream(String fileName) throws FileNotFoundException FileOutputStream(String fileName) throws FileNotFoundException
The filename specifies the name of the file that you want to open.when you create an input stream the file does not exist Then FileNotFoundException is thrown.
For the output stream if the file cannot be opened as consider as FileNotFoundException is thrown.
Its an subclass of IO Exception.
Failure to close the file is can result in memoryleaks because of unused resources remaining allocated.
In and upto JDK7 close() is used to close the file which is not needed.
To read from a file you can use the version of read() that is defined within FileInputStream().
It reads a single byte from a file and return as an integer.
Example:
import java.io.*;
class ShowFile {
public static void main(String args[])
{
int i;
FileInputStream fin = null;
// First, confirm that a filename has been specified.
if(args.length != 1) {
System.out.println("Usage: ShowFile filename");
return;
}
// The following code opens a file, reads characters until EOF
// is encountered, and then closes the file via a finally block.
try {
fin = new FileInputStream(args[0]);
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
} catch(FileNotFoundException e) {
System.out.println("File Not Found.");
} catch(IOException e) {
System.out.println("An I/O Error Occurred");
} finally {
// Close file in all cases.
try {
if(fin != null) fin.close();
} catch(IOException e) {
System.out.println("Error Closing File");
}
}
}
}
Automatically Closing a File:
- Close() used to close the file which are no linger needed.
- In which there is another way to manage the resources such as file stream for automating the closing process
- its name is Automatic Resource management.
- Forgetting to close a file causes memory leaks and cause many problems defined by java.lang.
In these program the input and output are open and close by these,
try (FileInputStream fin = new FileInputStream(args[0]); FileOutputStream fout = new FileOutputStream(args[1]))
After this try block ends, both fin and fout will have been closed
Applets:
- Applets are the small application that are accessed on the internet server transported to internet automatically installed and run as a part of web document.
After an applet arrives on the client it has limited access
to resources so it can produce a graphical user interface and runs various computations
without introducing the risk of viruses or breaching data integrity.Applet interact through the GUI not through console-based I/O classes.It uses AWT
Another commonly used GUI for applets is Swing.
The second import statement import the applet package which contains the class applet.
The paint() method has one parameter type is called graphics and its context where it is running.
Notice that applet does not have a main method().
applet execute the execution when the name of the class is passed to its applet viewer or its network browser.
Two ways we can run an applet. such as
1.Executing the applet within a java compatible web browser or under an applet viewer.
2.Applet viewer executes your applet in the window.
A short HTML text file can be used to execute the applet in the web browser that tags the load in applet.
With these three steps we can compile easily as edit,compile and execute.
User I/O is not accomplished with Java’s stream I/O classes. Instead, applets use
the interface provided by a GUI framework.
The transient and volatile modifiers:
- When a instance variable is declared as transient then its value does not persist when an object is stored.
- The volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.
- Program involves multithreading it will tends us to share two or more threads at the same variable.
- The real or master copy of the variable is updated at various time such as when synchronized method is entered.
Using instance of:
- knowing the type of an object during run time is useful.
- Many invalid casts can be caught at compile time.
- casts involving class hierarchies can produce invalid casts that can be detected only at run time.
- Example: A is superclass and B and C are subclass.In these A can pass to B or C to A are valid .but B to C is invalid(no viceversa) are allowed.
Java provides the run-time operator instanceof to answer this question.
objref instanceof typeobjref is an instance of class.
type is an classtype.
Strictfp:
strictfp is a keyword in the Java programming language that restricts floating-point calculations to ensure portability.
The strictfp command was introduced into Java with the Java virtual machine (JVM) version 1.2 and is available for use on all currently updated JavaVMs.
Problems with Native Methods:
- Native methods seem to offer great promise, because they enable you to gain access to the existing base of library routines.
Potential Security Risk:
- Native method executes the actual machine code and it can gain access to any part of the system.
- Native code confined to java execution environment.And this could allow you to virus infection.
- so the unsigned applets cannot be used in native methods.
- Also the loading of DLLs (Dynamic Link Library) is restricted.
Loss of portability:
- The native code contained in DLLs must be present on the machine that is executing the java program.
- Java application that uses native methods will be able to run only on machine for which compatible DLLs are installed.
Using Assert:
- New addition to Java is the keyword assert.
- It is used during program development to create an assertion which is a condition that should be true during the execution of the program.
And then there are two statements,
assert condition;
Condition is an expression that must evaluate to a Boolean result and if the condition is true no action takes place and if the condition is false then assertion fails and default.AssertionError is obtained.
assert condition: expr ;
expr is a value that is passed to the AssertionError constructor.This value is converted into string format and assigned if an assertion fails.
Assertion Enabling and Disabling Options:
- You can enable or disable an specific package by specifying its name followed by three periods of the -ea or -da option.
- Example:
To enable a pack in mypack;
-ea:mypack.....
To disable a pack in mypack;
-da:mypack......
For individually a pack in mypack;
-ea:mypack
The general form are,
import static pkg.type-name.static-member-name;
Here, type-name is the name of a class or interface that contains the desired static member.
Its full package name is specified by pkg.
The name of the member is specified by static member-name.
Invoking Overloaded Constructors Through this( ):
- When this( ) is executed, the overloaded constructor that matches the parameter list specified by arg-list is executed first.
- If there are any statements inside the original constructor, they are executed.
- The call to this( ) must be the first statement within the constructor.
- There are two restrictions you need to keep in mind when using this( ). First, you cannot use any instance variable of the constructor’s class in a call to this( ).
- You cannot super( ) and this( ) in the same constructor because each must be the first statement in the constructor.