Tuesday, June 21, 2011

InputStreams & Output Streams



Prior to JDK 1.1, the input and output classes (mostly found in the java.io package) only supported 8-bit byte streams. The concept of 16-bit Unicode character streams was introduced in JDK 1.1. While byte streams were supported via the java.io.InputStream and java.io.OutputStream classes and their subclasses, character streams are implemented by the java.io.Reader and java.io.Writer classes and their subclasses.


Methods defined in InputStream :


available() – bytes of input available for reading will be returned by this method.
close() – closes the input source.IOException will be generated if further reading continues.
mark(int numberofBytes) – Responsible to put a mark at the current point in the input stream .Validity will be
until you read those number of bytes
markSupported() – returns Boolean value true if this feature of mark()/reset() is supported.
read() –next available bytes integer representation in the input returned by this method .
reset() – For resetting the input pointer to previous set mark.
skip(long numberofBytes) – ignores the numberofBytes of input and returns the numberofBytes ignored
actually.


ByteArrayInputStream
Example :


byte b[] = tmp.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(b);

while ((c = in.read()) != -1) {
System.out.print(Character.toUpperCase((char) c));
}

FileInputStream:
File file = new File("DevFile.txt");

int ch;
StringBuffer strContent = new StringBuffer("");
FileInputStream fin = null;

try {
fin
= new FileInputStream(file);

while ((ch = fin.read()) != -1)
strContent
.append((char) ch);

fin
.close();
ObjectInputStream :
The ObjectInputStream class enables you to read Java objects from InputStream's instead of only bytes. You wrap an InputStream in a ObjectInputStream and then you can read objects from it. Here is an example:

ObjectInputStream input = new ObjectInputStream(
new FileInputStream("object.data"));

MyClass object = (MyClass) input.readObject();
//etc.

input.close();
BufferedInputStream

A BufferedInputStream wrapped around a FileInputStream, though, will request data from the FileInputStream in big chunks (512 bytes or so by default, I think.) Thus if you read 1000 characters one at a time, the FileInputStream will only have to go to the disk twice. This will be much faster!
  1. FileInputStream fis = new FileInputStream("MyFile.dat");
  2. BufferedInputStream bis = new BufferedInputStream(fis);
  3. int c;
  4. while ((c = bis.read) != -1) {
  5. // Do something with the single byte in "c";
  6. }
  7. bis.close(); // "fis" gets closed automatically
Missing, unflushed output to System.out is a common newbie problem. You can use a shutdown hook (see Runtime.addShutdownHook()) to ensure data will be flushed; an industrial-strength logging package should definitely do so.

DataInputStream :

it also implements DataInput, interface.
A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.




double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
int[] units = { 12, 8, 13, 29, 50 };
String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" };

DataOutputStream dos = new DataOutputStream(
new FileOutputStream("c:/invoice1.txt"));
for (int i = 0; i < prices.length; i ++) {
dos.writeDouble(prices[i]);
dos.writeChar('\t');
dos.writeInt(units[i]);
dos.writeChar('\t');
dos.writeChars(descs[i]);
dos.writeChar('\n');
}
dos.close();

DataInputStream dis = new DataInputStream(new FileInputStream("c:/invoice1.txt"));

double price;
int unit;
String desc;
double total = 0.0;

try {
while (true) {
price = dis.readDouble();
dis.readChar(); // throws out the tab
unit = dis.readInt();
dis.readChar(); // throws out the tab
desc = dis.readLine();
System.out.println("You've ordered " + unit + " units of " + desc + " at $" + price);
total = total + unit * price;
}
} catch (EOFException e) {
}

PushbackInputStream :


A PushbackInputStream adds functionality to another input stream, namely the ability to "push back" or "unread" one byte. This is useful in situations where it is convenient for a fragment of code to read an indefinite number of data bytes that are delimited by a particular byte value; after reading the terminating byte, the code fragment can "unread" it, so that the next read operation on the input stream will reread the byte that was pushed back. For example, bytes representing the characters constituting an identifier might be terminated by a byte representing an operator character; a method whose job is to read just an identifier can read until it sees the operator and then push the operator back to be re-read.

class PushbackInputStreamDemo {
public static void main(String args[]) throws IOException {
String s = "if (a == 4) a = 0;\\n";
byte buf[] = s.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(buf);
PushbackInputStream f = new PushbackInputStream(in);
int c;
while ((c = f.read()) != -1) {
switch(c) {
case '=':
if ((c = f.read()) == '=')
System.out.print(".eq.");
else {
System.out.print("<-");
f.unread(c);
}
break;
default:
System.out.print((char) c);
break;
}
}
}
}


OutputStreams :

Methods defined in OutputStream are,

close() – This closes the output stream.
flush() – It flushes the output buffers.
write(int b) – this writes a byte to an output stream
write(byte buffer[]) - this writes an array of bytes to the output stream
write(byte buffer[], int offset, int numberofBytes) this writes a specified range of bytes from a
byte array to the output stream



PrintStream :

A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. Two other features are provided as well. Unlike other output streams, a PrintStream never throws an IOException; instead, exceptional situations merely set an internal flag that can be tested via the checkError method. Optionally, a PrintStream can be created so as to flush automatically; this means that the flush method is automatically invoked after a byte array is written, one of the println methods is invoked, or a newline character or byte ('\n') is written.

All characters printed by a PrintStream are converted into bytes using the platform's default character encoding. The PrintWriter class should be used in situations that require writing characters rather than bytes.


FileOutputStream out;
PrintStream ps; // declare a print stream object
try {
// Create a new file output stream
out = new FileOutputStream("myfile.txt");

// Connect print stream to the output stream
ps = new PrintStream(out);

ps.println ("This data is written to a file:");
System.err.println ("Write successfully");
ps.close();




Sources & Sinks:

Java 1.0 class

Corresponding Java 1.1 class
InputStream
Reader

converter: InputStreamReader

OutputStream
Writer

converter: OutputStreamWriter

FileInputStream
FileReader
FileOutputStream
FileWriter
StringBufferInputStream
StringReader
(no corresponding class)
StringWriter
ByteArrayInputStream
CharArrayReader
ByteArrayOutputStream
CharArrayWriter
PipedInputStream
PipedReader
PipedOutputStream
PipedWriter



Differences :

The main difference between BufferedReader and BufferedInputStream is that Reader's work on characters (text), wheres InputStream's works on raw bytes.


Arrays

  • arrays are Java objects
  • all Java arrays are technically one-dimensional. Two-dimensional arrays are arrays of arrays.
  • declaring an array does not create an array object or allocate space in memory; it creates a variable with a reference to an array
  • array variable declarations must indicate a dimension by using [] 

 // declares an array of integers
        int[] anArray;

        // allocates memory for 10 integers
        anArray = new int[10];
 
 
Accessing Arrays 
 
         int arrval[]= new int[10];
  ArrayList<Object> arrList= new ArrayList();
  
  for (int a: arrval) {
   
   
  }
  for (Object obj : arrList) {
   
  }