Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Sunday, 5 June 2016

How to read a file using BufferedInputStream?


  1. File Class is used for file operation like creating a file, reading a file, updating a file, deleting a file, creating of directories, file search operations.
  2. FileInputStream Class used for reading bytes from a file in a file system. This Class is useful for reading the stream of bytes, raw data like image& etc. FileReader Class is useful to read the stream of characters.
  3. BufferedInputStream  Class is extended with FileInputStream& added with additional functionality of store stream in a Buffer. With Buffer, we can do the operations like read stream, skip the bytes, mark, reset, update the stream as needed, ready with next byte and updating the stream as needed.


Read File Using Java BufferedInputStream Example.
This example shows how to read a file using available and read methods of Java BufferedInputStream.


package snippets11;
import java.io.*;

/**
 * Created by root on 15/3/16.
 */
public class ReadFileUsingBufferedInputStream {
    public static void main(String[] args) {
        File file=null;
        FileInputStream in=null;
        BufferedInputStream bf=null;

        try {
            file=new File("/home/suresh/temp/testjava.txt");
            in=new FileInputStream ( file );
            bf=new BufferedInputStream ( in );

            /*
             * BufferedInputStream has ability to buffer input into
             * internal buffer array.
             *
             * available() method returns number of bytes that can be
             * read from underlying stream without blocking.
             */

            //read file using BufferedInputStream
            while (bf.available ()>0){
                System.out.print((char)bf.read());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace ( );
        } catch (IOException e) {
            e.printStackTrace ( );
        }finally {
            //close the BufferedInputStream using close method
            try{
                if(bf != null)
                    bf.close();

            }catch(IOException ioe)
            {
                System.out.println("Error while closing the stream : " + ioe);
            }
        }
    }
}

How to read byte array using ByteArrayInputStream?


ByteArrayInputStream keep maintains a buffer and tracks the next byte to be supplied. With ByteArrayInputStream we can read bulk data and buffer is helpful for faster response.


Example Code:

package snippets11;
import java.io.ByteArrayInputStream;

/**
 * Created by root on 15/3/16.
 */
public class ByteArrayInputStreamExample {
    public static void main(String[] args) {
        String string="Programming World...";
        byte[] bytes=string.getBytes();

        ByteArrayInputStream ba=new ByteArrayInputStream(bytes);
        int ch;
        while((ch=ba.read())!=-1){
            System.out.print((char)ch);
        }
    }
}

click here.

basic data types in java

Data types in java are two type' s

  1. Primitive 
  2. Reference
Mostly Used Primitive Data Type' s
  1. boolean 
  2. char
  3. int
  4. byte
  5. float
  6. long
  7. double
  8. String
Data Type: boolean
Bytes: 1 bit.
Description: this data type represents 1 bit information, mostly used in the true/false conditions.
Possible values: true/false 


Data Type: char
Bytes: 16 bit unicode.
Description: this data type used to store character' s.

Data Type: int 
Bytes: 32 bit signed representation.
Description: this data type used to store integer of signed representation.

Data Type: byte 
Bytes: 8 bit signed representation.
Description: this data type used to store integer of signed representation, this type is useful when we need to store an array of integer's with max of 8 bit' s. so, we can save 24 bit' s when compare to the int data type.


Data Type: float 
Bytes: 32 bit
Description: this data type used to store integer with single-precision/decimal values.


Data Type: long
Bytes: 64 bit signed representation.
Description: this data type used to store integer with single-precision/decimal values.


Data Type: double
Bytes: 64 bit signed representation.
Description: this data type used to store integer with single-precision/decimal values.

Data Type: String
Bytes: 64 bit signed representation.
Description: this data type used to store integer with single-precision/decimal values.


Example code:
package snippets1;

/**
 * Created by root on 11/3/16.
 */
public class DataTypeTest {

    public static void main(String args[]){

        boolean status = true;
        char a = 'A';
        int b = 12;
        byte e = 12;
        float f=3.14f;
        long c = 1235;
        double d = 12345.23;
        String str = "programming";

        System.out.println("boolean: "+status+"\nchar: "+a+"int: "+b+"\nbyte: "+e+"\nfloat: "+f+"\nlong: "+c+"\ndouble: "+d);
    }
}

Command line example in java

Passing command line arguments in java

1. check the number argument's passed, exit the program with status success when you received insufficient command line arguments.

        if(args.length==0){
            System.out.println("Insufficient Arguments..");
            System.exit(0);
        }

2.  Parse the arguments to Integer from String.
      System.out.print("sum="+Integer.parseInt(arg1)+Integer.parseInt(arg2));

for complete code click here.

Tuesday, 22 March 2016

java example on data types

package snippets1;

/*
 *
 * 
Created by root on 11/3/16. */

public class DataTypeTest
{
  public static void main(String args[]){
  boolean status = true;
  char a = 'A';
  int b = 12;
  byte e = 12;
  float f=3.14f;
  long c = 1235;
  double d = 12345.23;
  String str = "programming";

  System.out.println("boolean: "+status+"\nchar: "+a+"int: "+b+"\nbyte: "+e+"\nfloat: "+f+"\nlong: "+c+"\ndouble: "+d);
        }
} 

Sunday, 13 March 2016

Java mysql crud perations

import java.sql.*;
//import java.util.logging.Logger;
//import java.util.logging.Level;
public class Base {
private static final String ConnectionString="jdbc:mysql://localhost/emp";
private static final String DBUser="root";
private static final String DBPass="mysql";
protected static Connection conn=null;
protected static Statement stmt=null;
protected static ResultSet rs=null;
//private static final Logger logger = Logger.getLogger(Base.class.getName());
public static void main(String[] args) {
try{
Base b=new Base();
// logger.entering(Base.class.getName(), "doIt");
b.insert();
b.update();
//b.delete();
b.read();
}catch(Exception e){
e.printStackTrace();
}
}
public Base(){
try{
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(ConnectionString,DBUser,DBPass);
if(conn!=null){
System.out.println("connection established..");
}else{
System.out.println("connections not established..");
}
System.out.println(conn);
}catch(Exception e){
e.printStackTrace();
}
}
public boolean insert(){
try{
stmt=conn.createStatement();
String query=" insert into profile values(\"suresh\",102);";
int res=stmt.executeUpdate(query);
//System.out.println("result of executeUpdate"+res);
if(res==0){
//System.out.println("record not inserted");
return false;
}
else{
//System.out.println("record Inserted");
return true;
}
}catch(Exception e){
e.printStackTrace();
}
return false;
}
public boolean update(){
try{
stmt=conn.createStatement();
String Query="update profile set id=103 where name=\"ramesh\"";
int res=stmt.executeUpdate(Query);
if(res==0){
return false;
}else{
return true;
}
}catch(Exception e){
e.printStackTrace();
}
return false;
}
public boolean delete(){
try{
stmt=conn.createStatement();
String Query="delete from profile where name=\"ramesh\"";
int res=stmt.executeUpdate(Query);
if(res==0){
return false;
}else{
return true;
}
}catch(Exception e){
e.printStackTrace();
}
return true;
}
public boolean read(){
try{
stmt=conn.createStatement();
String Query="select * from profile";
rs=stmt.executeQuery(Query);
while(rs.next()){
String name=rs.getString("name");
int id=rs.getInt("id");
System.out.println("name="+name+" --> "+"id="+id);
}
}catch(Exception e){
e.printStackTrace();
}
return true;
}
}