Saturday, November 1, 2014

Java byte array Pro



Read partial byte array using Byte Array Input Stream

import java.io.ByteArrayInputStream;
public class ReadPartialByteArray
 {
 public static void main(String[] args)
{
String str = "Byte Array InputStream Example";
byte[] bytes = str.getBytes();
ByteArrayInputStream bis = new ByteArrayInputStream(bytes, 5, 5);
int ch;
while ((ch = bis.read()) != -1)
{
System.out.print((char)ch);
    }
  }
}

Java String Buffer to Input Stream

import java.io.ByteArrayInputStream;
import java.io.InputStream;
public class StringBufferToInputStreamExample
 {
public static void main(String args[])
{
StringBuffer sbf = new StringBuffer("StringBuffer to InputStream Example");
byte[] bytes = sbf.toString().getBytes();
InputStream inputStream = new ByteArrayInputStream(bytes);           
System.out.println("StringBuffer converted to InputStream");
   }
}


Java Pushback Input Stream

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PushbackInputStream;
public class JavaPushbackInputStreamExamples
{
 public static void main(String[] args)
{
String strExpression = "a = a++ + b;"; byte bytes[] = strExpression.getBytes();  ByteArrayInputStream bis = new ByteArrayInputStream(bytes); PushbackInputStream pis = new PushbackInputStream(bis);
int ch;
try
{
while( (ch = pis.read())!= -1)
{
if(ch == '+')
{
if( (ch = pis.read()) == '+')
{
System.out.print("Plus Plus");
}
else
{
pis.unread(ch);
System.out.print("+");
}
}
else
{
System.out.print((char)ch);
    }
  }
}
catch(IOException ioe)
{
System.out.println("Exception while reading" + ioe);
    }
  }
}

Java String to Input Stream

import java.io.ByteArrayInputStream;
import java.io.InputStream;
public class JavaStringToInputStreamExample
{
public static void main(String args[])
{
String str1 = "Java convert String to InputStream Example";
byte[] bytes = str1.getBytes();
InputStream inputStream = new ByteArrayInputStream(bytes);
   }
}

Read boolean from file using Data Input Stream

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ReadBooleanFromFile
{
public static void main(String[] args)
{
String strFilePath = "C://FileIO//readBoolean.txt";
try
{
FileInputStream fin = new FileInputStream(strFilePath); DataInputStream din = new DataInputStream(fin);
boolean b = din.readBoolean();         
System.out.println("boolean : " + b);
din.close();   
}
catch(FileNotFoundException fe)
{
System.out.println("FileNotFoundException : " + fe);
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe);
    }
  }
}

No comments:

Post a Comment