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) {
   
  } 

Monday, March 28, 2011

Variables

Data Type Description Size Default Value
boolean true or false 1-bit false
char Unicode Character 16-bit \u0000
byte Signed Integer 8-bit (byte) 0
short Signed Integer 16-bit (short) 0
int Signed Integer 32-bit 0
long Signed Integer 64-bit 0L
float Real number 32-bit 0.0f
double Real number 64-bit 0.0d

  1. Declaring an uninitialised variable at class level is valid and it takes a default value of 0 or null
  2. Declaring an uninitialised local variable and referencing/using it is allowed (compilation error - variable is not initialized)
Representing different number system :

     int decVal = 26;     // The number 26, in decimal
int octVal = 032; // The number 26, in octal
int hexVal = 0x1a; // The number 26, in hexadecimal
int binVal = 0b11010; // The number 26, in binary

Representing float
:

double d1 = 123.4;
double d2 = 1.234e2; // same value as d1, but in scientific notation


Underscore
:

The following example shows other ways you can use the underscore in numeric literals:

long creditCardNumber = 1234_5678_9012_3456L;
long socialSecurityNumber = 999_99_9999L;
float pi = 3.14_15F;
long hexBytes = 0xFF_EC_DE_5E;
long hexWords = 0xCAFE_BABE;
long maxLong = 0x7fff_ffff_ffff_ffffL;
byte nybbles = 0b0010_0101;
long bytes = 0b11010010_01101001_10010100_10010010;

You can place underscores only between digits; you cannot place underscores in the following places:

* At the beginning or end of a number
* Adjacent to a decimal point in a floating point literal
* Prior to an F or L suffix
* In positions where a string of digits is expected

The following examples demonstrate valid and invalid underscore placements in numeric literals:

float pi1 = 3_.1415F; // Invalid; cannot put underscores adjacent to a decimal point
float pi2 = 3._1415F; // Invalid; cannot put underscores adjacent to a decimal point
long socialSecurityNumber1
= 999_99_9999_L; // Invalid; cannot put underscores prior to an L suffix

int x1 = _52; // This is an identifier, not a numeric literal
int x2 = 5_2; // OK (decimal literal)
int x3 = 52_; // Invalid; cannot put underscores at the end of a literal
int x4 = 5_______2; // OK (decimal literal)

int x5 = 0_x52; // Invalid; cannot put underscores in the 0x radix prefix
int x6 = 0x_52; // Invalid; cannot put underscores at the beginning of a number
int x7 = 0x5_2; // OK (hexadecimal literal)
int x8 = 0x52_; // Invalid; cannot put underscores at the end of a number

int x9 = 0_52; // OK (octal literal)
int x10 = 05_2; // OK (octal literal)
int x11 = 052_; // Invalid; cannot put underscores at the end of a number