Friday, October 31, 2014

Java Byte array



Write byte array to a file using File Output Stream

import java.io.*;
public class WriteByteArrayToFile
{
public static void main(String[] args)
{
String strFilePath = "C://FileIO//demo.txt";
try
{
FileOutputStream fos = new FileOutputStream(strFilePath);
String strContent = "Write File using Java FileOutputStream example !";
fos.write(strContent.getBytes());
fos.close();
      
}
catch(FileNotFoundException ex)
{
System.out.println("FileNotFoundException : " + ex);
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe);
      }
   }
}

Write file using File Output Stream

import java.io.*; 
public class WriteFile
{
public static void main(String[] args)
{
String strFilePath = "C://FileIO//demo.txt";
try
{
FileOutputStream fos = new FileOutputStream(strFilePath);
byte b = 01;
fos.write(b);
fos.close();
}
catch(FileNotFoundException ex)
{
System.out.println("FileNotFoundException : " + ex);
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe);
    
   }
}

Read character from console using Input Stream

import java.io.IOException;
public class ReadCharFromConsoleExample
{
public static void main(String[] args)
 {
int iChar = 0;
System.out.println("Read user input character example");
try
{
System.out.println("Enter a character to continue");
iChar = System.in.read();
System.out.println("Char entered was : " + (char)iChar);
}
catch(IOException e)
{
System.out.println("Error while reading : " + e);
    }
  }
}

Read line of characters from console using Input Stream

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadLineFromConsoleExample
{
public static void main(String[] args)
{
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
String strLine = null;
System.out.println("Reading line of characters from console");
System.out.println("Enter exit to quit");
try
{
                         
while( (strLine = br.readLine()) != null)
{
if(strLine.equals("exit"))
break;
System.out.println("Line entered : "  + strLine);
}
br.close();                    
}
catch(Exception e)
{
System.out.println("Error while reading line from console : " + e);
     }
    }
}

No comments:

Post a Comment