Sei sulla pagina 1di 42

Exception Handling Examples

Exception in java with Example Program


1. Exception

An exception is a problem that arises during the execution of a program

Exception is a runtime error


An exception can occur for many different reasons, including the following:

A user has entered invalid data.

A file that needs to be opened cannot be found.

A network connection has been lost in the middle of communications, or the JVM has run out of memory.
Types of error:
Compile time error
Compile time error is any type of error that prevent a java program compile like a syntax error, a class not found, a bad file name for the defined
class, and so on.
Run time error
A runtime error means an error which happens, while the program is running. To deal with this kind of errors java define Exceptions. Exceptions
are objects represents an abnormal condition in the flow of the program. It can be either checked or unchecked.
1.2 Types of exception

Checked Exceptions

Errors

Runtime Exceptions
Checked Exception( handled at compile time.)
Environmental error that cannot necessarily be detected by testing; e.g. disk full, broken socket, database unavailable, etc. The Exception problem
can be overcome by implementing Try-Catch block.
Error
Virtual machine error: class not found, out of memory, no such method, illegal access to private field, etc
Runtime Exception(Unchecked Exception)
Programming errors that should be detected in testing: index out of bounds, null pointer, illegal argument, etc.
The Compiler never checks the Unchecked exception during the program compilation. For example, Dividing any number by zero is an unchecked
exception.
1.3Exception Hierarchy
1.4 Exception management
Exception can be managed through five keywords in java
1.try
2.catch
3.finally
4.throw
5.throws
try-used to keep the code that going to throw error
catch-used to catch and process the error thrown by try block
example for try /catch block:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

class Sam
{
public static void main(String args[])
{
int k=0;
int msg;
String s1=args[0];
String s2=args[1];
int i=Integer.parseInt(s1);
int j=Integer.parseInt(s2);
try
{
k=i/j;
System.out.println(k);
}
catch(Exception e)
{
System.out.println(error);
}
}

finally-A finally block of code always executes, whether or not an exception has occurred. Finally used for avoid resource leakage .
The finally clause is executed after a try-catch block has been executed
?

1
2
3
4
5
6

try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{

7
8
9
10
11
12
13
14
15
16

//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}

Example for finally:


?

Connection conn; // opened before, at the beginning of

1 the method
?

1
2
3
4
5
6
7

try {
// execute a query
} catch (SQLException e) {
// handles the exception, dispalying a message, whatever
} finally {
conn.close();
}

throw- throw is used to actually throw the exception


throws- throws is declarative for the method. They are not interchangeable.
The following code shows how to handle multiple exceptions using the throws keyword.
?

1 public class Example


{
2
public void exceptionExample()
3
{
4
try
{
5
// statements
6
check();
7
}
8
catch(Exception e)
9
{
//statements
10
}
11
}
12
// multiple exceptions separated by a comma
13
14
void check() throws
15 NullPointerException,NegativeArraySizeException
{
16
if (flag < 0)
17
throw new NullPointerException();
18
if (arrsize < 0)
19
throw new NegativeArraySizeException();
}
20
21 }

22
23
24
Primarykey
This tutorial explains how to set a primary key for a table in mysql using java statement example, Load the mysql driver using Class.forName
method and create a connection to communicate with mysql database and then create a statement object to send and receive from java code and
use executeUpdate to execute the query. If we wants to change a column constrain to primary key using java use this tutorial

Java code:
?

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

5
6

public class Primarykey {

7
8
9
10
11

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

12
13
14
15

String Driver = "com.mysql.jdbc.Driver";


String url = "jdbc:mysql://localhost/test";
String uName ="root";

16

String pwd = "root";

17

Connection conn=null;

18
19

try {

20

Class.forName(Driver).newInstance();

21

conn = DriverManager.getConnection(url,

22 uName, pwd);
Statement stmt = conn.createStatement();

23
24

String sql = "Alter table student Add


primary key (Roll_No)";

25
26
27

stmt.executeUpdate(sql);
System.out.println("primarykey added
sucessfully");

28
} catch (ClassNotFoundException e) {

29

// TODO Auto-generated catch block

30

e.printStackTrace();

31
}

32

catch (SQLException e) {

33

// TODO Auto-generated catch block

34

e.printStackTrace();

35

36

catch (Exception e) {

37

// TODO Auto-generated catch block

38

e.printStackTrace();

39

40

finally{
try {

41

conn.close();

42

} catch (SQLException e) {

43

// TODO Auto-generated catch block

44

e.printStackTrace();

45
}

46

47
48
49

50
51 }
Output:

Unique statement:
This tutorial explains how to update a column constrainto unique in a table in mysql using java statement example, Load the mysql driver using
Class.forName method and create a connection to communicate with mysql database and then create a statement object to send and receive
from java code and use executeUpdate to execute the query.

Java code:
?

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

6
7
8
9

public class Unique {


/**
* @param args
*/

10
11

public static void main(String[] args) {


// TODO Auto-generated method stub

12
13
14

String Driver = "com.mysql.jdbc.Driver";


String url = "jdbc:mysql://localhost/sec";

15

String uName ="root";

16

String pwd = "root";

17

Connection conn=null;

18
19

try {

20

Class.forName(Driver).newInstance();

21

conn = DriverManager.getConnection(url, uName, pwd);


Statement stmt = conn.createStatement();

22

String sql = "create table student2(roll_no int NOT NULL,Name varchar(25

23 varchar(5),city varchar(25),Unique(roll_no))";
24

stmt.executeUpdate(sql);

25

System.out.println("create table sucessfully");

26
27

} catch (ClassNotFoundException e) {

28

// TODO Auto-generated catch block

29

e.printStackTrace();

30
31

}
catch (SQLException e) {
// TODO Auto-generated catch block

32

e.printStackTrace();

33
34

}
catch (Exception e) {

35

// TODO Auto-generated catch block

36
37
38
39

e.printStackTrace();
}
finally{
try {

40
41

conn.close();
} catch (SQLException e) {

42

// TODO Auto-generated catch block

43

e.printStackTrace();

44

45
46

47
48

49
50 }
51
Output:

Create statement:
This tutorial explains how to Create a table in mysql using java statement example, Load the mysql driver using Class.forName method and create
a connection to communicate with mysql database and then create a statement object to send and receive from java code

and use

executeUpdate to execute the query . The following codes in this java tutorial explain how to Create a table named staff with columns as Fields,
Type, Null, Key, Default, Extra .

Java code:
?

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

6
7
8
9

public class CreateTable {


/**
* @param args
*/

10

public static void main(String[] args) {

11

// TODO Auto-generated method stub

12
13

String Driver = "com.mysql.jdbc.Driver";

14

String url = "jdbc:mysql://localhost/test";

15

String uName ="root";

16
17

String pwd = "root";


Connection conn=null;

18
19

try {
Class.forName(Driver).newInstance();

20

conn = DriverManager.getConnection(url, uName, pwd);

21

Statement stmt = conn.createStatement();

22

String sql = "create table staff(name varchar(25),department


varchar(5),subject_name
varchar(25))";
23
stmt.executeUpdate(sql);

24

System.out.println("CreateTable sucessfully");

25
26
27

} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block

28
29
30

e.printStackTrace();
}
catch (SQLException e) {

31

// TODO Auto-generated catch block

32

e.printStackTrace();

33

34

catch (Exception e) {

35

// TODO Auto-generated catch block

36

e.printStackTrace();

37

38

finally{

39
40

try {

41

conn.close();

42

} catch (SQLException e) {

43

// TODO Auto-generated catch block

44

e.printStackTrace();
}

45
}

46
47
}

48
49
50

51
Output:

Delete statement:
This tutorial explains how to delete a single row from a table in mysql using java statement example, Load the mysql driver using Class.forName
method and create a connection to communicate with mysql database and then create a statement object to send and receive from java code and
use executeUpdate to execute the query. If user wants to delete a one or more rows from a table delete query will helps us to do it. Suppose if we
want to delete the details of ravi from student table we can use this sample code to delete it.

create table:
?

1 create table student(Roll_No int(5),Name varchar(25),


2
3 Department varchar(7),Address varchar(30));
4

5 Query OK, 0 rows affected (0.06 sec)


Input:

Java code:
?

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

6
7
8
9

public class Delete {


/**
* @param args
*/

10
11

public static void main(String[] args) {


// TODO Auto-generated method stub

12
13
14

String Driver = "com.mysql.jdbc.Driver";


String url = "jdbc:mysql://localhost/test";

15

String uName ="root";

16

String pwd = "root";

17

Connection conn=null;

18
19
20

try {
Class.forName(Driver).newInstance();
conn = DriverManager.getConnection(url,

21 uName, pwd);
Statement stmt = conn.createStatement();

22
23

String sql = "delete from student where


name='ravi'";

24
25
26

stmt.executeUpdate(sql);
System.out.println("Data deleted
sucessfully");

27
} catch (ClassNotFoundException e) {

28

// TODO Auto-generated catch block

29

e.printStackTrace();

30
}

31

catch (SQLException e) {

32

// TODO Auto-generated catch block

33

e.printStackTrace();

34

35

catch (Exception e) {

36

// TODO Auto-generated catch block

37

e.printStackTrace();

38

39

finally{
try {

40

conn.close();

41

} catch (SQLException e) {

42

// TODO Auto-generated catch block

43

e.printStackTrace();

44
}

45

46
47
48

49
50
}

51
OUTPUT:

Data deleted successfully

SQL INSERT INTO Statement:


This tutorial explains how to insert a single row into a table in mysql using java statement example, Load the mysql driver using Class.forName
method and create a connection to communicate with mysql database and then create a statement object to send and receive from java code and
use executeUpdate to execute the query. If we wants to add a new record into the table or to add a new row, just use this following code to
update the table with new record.
create table:
?

1 create table student(Roll_No int(5),Name varchar(25),


2
3 Department varchar(7),Address varchar(30));
4
5 Query OK, 0 rows affected (0.06 sec)
Input:

Java code:
?

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

5
6
7
8
9
10

public class CreateTable {


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

11
12
13

String Driver = "com.mysql.jdbc.Driver";


String url = "jdbc:mysql://localhost/test";

14

String uName ="root";

15

String pwd = "root";

16

Connection conn=null;

17
18

try {

19

Class.forName(Driver).newInstance();

20

conn = DriverManager.getConnection(url,

21
22
23
24

uName, pwd);
Statement st= conn.createStatement();
String sql="insert into student
values('101','suresh','cse','chennai')";
st.executeUpdate(sql);
System.out.println("Data Inserted

25 sucessfully");
26

27
} catch (ClassNotFoundException e) {

28

// TODO Auto-generated catch block

29

e.printStackTrace();

30

31

catch (SQLException e) {

32

// TODO Auto-generated catch block

33

e.printStackTrace();

34

35

catch (Exception e) {

36

// TODO Auto-generated catch block

37

e.printStackTrace();

38

39

finally{
try {

40

conn.close();

41

} catch (SQLException e) {

42

// TODO Auto-generated catch block

43

e.printStackTrace();

44
}

45

46
47

48
49

50
OUTPUT:

Data Inserted successfully

Alter statement:
This tutorial explains how to alter a table in mysql using java statement example, Load the mysql driver using Class.forName method and create a
connection to communicate with mysql database and then create a statement object to send and receive from java code and use executeUpdate
to execute the query . While creating student table there is only four columns namely Roll_NO, Name, Department, Address. The following codes
in this java tutorial explain how to alter a table and create a new column.

create table:
?

1 create table student(Roll_No int(5),Name varchar(25),


2
3 Department varchar(7),Address varchar(30));
4
5 Query OK, 0 rows affected (0.06 sec)
Input:

Java code:
?

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

6
7
8
9
10
11
12

public class Alter {


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

13
14
15
16
17

String Driver = "com.mysql.jdbc.Driver";


String url = "jdbc:mysql://localhost/test";
String uName ="root";
String pwd = "root";
Connection conn=null;

18
19

try {

20

Class.forName(Driver).newInstance();

21
22

conn = DriverManager.getConnection(url,
uName, pwd);
Statement stmt = conn.createStatement();

23

String sql = "Alter table student Add

24 Date_of_birth date";
stmt.executeUpdate(sql);

25
26

System.out.println("table Alter
sucessfully");

27
28

} catch (ClassNotFoundException e) {

29

// TODO Auto-generated catch block

30

e.printStackTrace();

31

32

catch (SQLException e) {

33
// TODO Auto-generated catch block

34

e.printStackTrace();

35

36

catch (Exception e) {

37

// TODO Auto-generated catch block

38

e.printStackTrace();

39

40

finally{

41

try {
conn.close();

42

} catch (SQLException e) {

43

// TODO Auto-generated catch block

44

e.printStackTrace();

45
}

46
47
48

}
}
}

49
OUTPUT:

table Alter sucessfully

Update statement:
This tutorial explains how to update a existing row in a table in mysql using java statement example, Load the mysql driver using Class.forName
method and create a connection to communicate with mysql database and then create a statement object to send and receive from java code and
use executeUpdate to execute the query. Use update query to update a existing data in a table this will be helpful in modifying record in a table.
create table:
?

1 create table student(Roll_No int(5),Name varchar(25),


2
3 Department varchar(7),Address varchar(30));
4
5 Query OK, 0 rows affected (0.06 sec)
Input:

Java code:
?

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

6
7
8
9

public class UpdateTable {


/**
* @param args
*/

10
11

public static void main(String[] args) {


// TODO Auto-generated method stub

12
13

String Driver = "com.mysql.jdbc.Driver";

14

String url = "jdbc:mysql://localhost/test";

15

String uName ="root";

16

String pwd = "root";

17

Connection conn=null;

18
19

try {
Class.forName(Driver).newInstance();

20

conn = DriverManager.getConnection(url, uName, pwd);

21

Statement stmt = conn.createStatement();

22

String sql = "UPDATE student SET Name='tamil' where


Roll_No='106'
and Department='cse'";
23

24

stmt.executeUpdate(sql);

25

System.out.println("Data update sucessfully");

26
27

} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block

28

e.printStackTrace();

29
30

}
catch (SQLException e) {

31

// TODO Auto-generated catch block

32
33
34

e.printStackTrace();
}
catch (Exception e) {

35

// TODO Auto-generated catch block

36

e.printStackTrace();

37

38

finally{

39

try {

40
41

conn.close();

42

} catch (SQLException e) {

43

// TODO Auto-generated catch block

44

e.printStackTrace();

45

}
}

46
47
}

48
49
50

51
OUTPUT:

Data Update successfully

Select statement:
This tutorial explains how to fetch or retrieve all row in a table in mysql using java statement example, Load the mysql driver using Class.forName
method and create a connection to communicate with mysql database and then create a statement object to send and receive from java code and
use executeQuery to execute the query and use a resultset object to hold the data as java object. If we wants to add a new record into the table
or to add a new row, just use this following code to update the table with new record.
create table:
?

mysql> create table student(Roll_No int(5),Name


varchar(25),

2
3 Department varchar(7),Address varchar(30));
4
5 Query OK, 0 rows affected (0.06 sec)
Input:

Java code:
?

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

6
7

public class Select {

8
9
10

/**
* @param args
*/

11
12

public static void main(String[] args) {


// TODO Auto-generated method stub

13
14
15

String Driver = "com.mysql.jdbc.Driver";


String url = "jdbc:mysql://localhost/test";

16

String uName ="root";

17

String pwd = "root";

18

Connection conn=null;

19
20

try {
Class.forName(Driver).newInstance();

21
22

conn = DriverManager.getConnection(url,
uName, pwd);

23
24
25

Statement stmt = conn.createStatement();


ResultSet rs = stmt.executeQuery("SELECT *
FROM student");
System.out.println("select statement

26 sucessfully used");
27

while (rs.next()) {

28

String Roll_no=
rs.getString("Roll_no");

29

String name= rs.getString("name");

30

String department=

31 rs.getString("department");
32

String address=
rs.getString("address");

33

System.out.print(Roll_no+ "\t");

34

System.out.print(name+ "\t");

35

System.out.print(department+ "\t");

36

System.out.println( address+ "\t");

37

38

} catch (ClassNotFoundException e) {

39

// TODO Auto-generated catch block

40

e.printStackTrace();

41

42

catch (SQLException e) {
// TODO Auto-generated catch block

43

e.printStackTrace();

44
45

catch (Exception e) {

46
47

// TODO Auto-generated catch block

48

e.printStackTrace();
}

49

finally{

50

try {

51

conn.close();

52

} catch (SQLException e) {

53

// TODO Auto-generated catch block

54

e.printStackTrace();

55

56

57
58

59
60 }
OUTPUT:
select statement sucessfully used:
101 suresh
103 arivu
104 muthu

cse dharmapuri
AE

trichy

ECE ariyalur

105 mani

EEE kovai

106 tamil

CSE trichy

107 Raja

IT

tanjur

BufferedInputStream example program for close() in java

1
2
3
4

/**
* @author

candidjava

* @description:BufferedInputStream example program for


close() in java
*/

5
6

import java.io.File;

import java.io.BufferedInputStream;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

10 import java.io.IOException;
11
12 public class ReadFileUsingBufferedInputStream {
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

public static void main(String[] args) {


File file = new
File("F:/Vikram/StaticInit.java");
BufferedInputStream bin = null;
try {
FileInputStream fin = new
FileInputStream(file);
bin = new BufferedInputStream(fin);
while (bin.available() > 0) {
System.out.print((char) bin.read());
}
} catch (FileNotFoundException e) {
System.out.println("File not found" + e);
} catch (IOException ioe) {
System.out.println("Exception while reading
the file " + ioe);
} finally {

try {

29

if (bin != null)

30

bin.close();

31
32
33

} catch (IOException ioe) {


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

34
}

35
}

36
}

Output
class A
{
{
System.out.print(Init);
}
Static
{
System.out.print(Static);
}
A()
{
System.out.print(Constructor);
}
}

Long Example Program for valueOf(String s)

/**

@author: candidjava

@description: valueOf(String s) is used to a long object holding


the value of specify string

4
5
6

*/
public class DeeValueOfStringLong
{

public static void main(String[] args) throws Exception

9
10
11

try{
String s="candid";//get the string
Long l=new Long(246);//get the long value
System.out.println(l.valueOf(s));// to return a long object

12 holding the value of specify string


13 }

14 catch(Exception e)//if the exception occur means catch the


exception

15
16
17

{
System.out.println(e.getMessage());//print the message
}

18 }
19 }
output:
For input string: candid

Long Example Program for valueOf(String s,int radix)

/**

@author: candidjava

@description: valueOf(String s,int radix) is return a Long object holding the value
by the string argument in the specified radix.

4
5

*/
public class DeeValueOfStringRadixLong

public static void main(String[] args) throws Exception

try{

10 String s="candid";//get the string

11 System.out.println(Long.valueOf(s,10));//to return a Long object holding the value r


by the string argument in the specified radix.

12
13
14

}
catch(Exception e)//if any exception occurs means catch exception
{

15 System.out.println(e.getMessage());//print exception message


16 }
17 }
18 }
output:
For input string: candid

Short Example Program for valueOf(String s,int radix)

/**

@author: candidjava

@description: valueOf(String s,int radix) this method is used to a Short object hold
represented by the string argument in the specified radix.

4
5

*/
public class ShortValueOf extends Dee

public static void main(String []args)

try{

10 String s="234";//initialize and declare the s value


11 int radix=16;//initialize and declare the radix value
12

Integer i=Integer.valueOf(s,radix);// a Short object holding the value represented b


//in the specified radix.

13 System.out.println(i);//to print the value i


14 }
15 catch(NumberFormatException nfe)//if the exception found mean catch this block

16

17 System.out.println(nfe.getMessage());//to print the exception massage


18 }
19 }
20 }
21 class Dee //sub class
22 {
23 Dee(){}
24
25
26

void Dee() throws NumberFormatException


{}
}

output
564

FileOutputStream example program for getFD() () in java

1
2
3
4

/**
*@author: candidjava
*@description: FileOutputStream example program for
getFD()() in JAVA
**/

5
6

import java.io.FileDescriptor;

import java.io.FileOutputStream;

import java.io.IOException;

9
10 public class FileOutputStreamDemo {
11
12

public static void main(String[] args) throws


IOException {
FileOutputStream fos = null;

13
FileDescriptor fd = null;

14

boolean bool = false;

15

try {

16

// create new file output stream

17

fos = new FileOutputStream("C://test.txt");

18

// get file descriptor instance

19

fd = fos.getFD();

20

// test if the file is valid

21

bool = fd.valid();

22

// print

23

System.out.print("Is file valid? " + bool);


} catch (Exception ex) {

24
25

// if an error occurs

26

ex.printStackTrace();
} finally {

27

if (fos != null)

28

fos.close();

29
}

30
31

}
}

32
Output
is file valid? true

FileInputStream example program for skip(long n) in java

1
2

/**
*@author: candidjava

*@description:

**/

import java.io.IOException;

import java.io.FileInputStream;

7
8
9

public class FileInputStreamDemo {


public static void main(String[] args) throws
IOException {

10

FileInputStream fis = null;

11

int i = 0;

12

char c;

13

try {

14

// create new file input stream

15

fis = new FileInputStream("C://test.txt");

16

// skip bytes from file input stream


fis.skip(4);

17

// read bytes from this stream

18

i = fis.read();

19

// converts integer to character

20

c = (char) i;

21

// prints

22

System.out.print("Character read: " + c);

23

} catch (Exception ex) {

24

// if any error occurs

25

ex.printStackTrace();

26

} finally {

27
28

// releases all system resources from the


streams
if (fis != null)

29
30

fis.close();
}

31
32

}
}

33
Output
Character read: E

FileOutputStream example program for write(int b) () in java

1
2
3
4

/**
*@author: candidjava
*@description: FileOutputStream example program for
write(int b)() in java
**/

5
6

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

9
10 public class FileOutputStreamDemo1 {
11
12
13
14
15

public static void main(String[] args) throws


IOException {
FileOutputStream fos = null;
FileInputStream fis = null;
byte b = 66;
int i = 0;

16

char c;

17

try {

18

// create new file output stream

19

fos = new FileOutputStream("C://test.txt");

20

// writes byte to the output stream

21

fos.write(b);

22
23

// flushes the content to the underlying


stream
fos.flush();

24

// create new file input stream

25

fis = new FileInputStream("C://test.txt");

26

// read till the end of the file

27

while ((i = fis.read()) != -1) {

28

// convert integer to character

29

c = (char) i;

30

// prints

31

System.out.print(c);

32

}
} catch (Exception ex) {

33
34

// if an error occurs

35

ex.printStackTrace();
} finally {

36
37

38 from stream

// closes and releases system resources

39

if (fos != null)

40

fos.close();

41

if (fis != null)

42

fis.close();
}

43
}

44
45

Output
B

FileInputStream example program for close() in java

/**

@program : FileInputStream example program for close()


in java

3
4
5

@author

: "candid"

@date

: 29.10.12

*/

6
7

import java.io.FileInputStream;

import java.io.IOException;

9
10 public class FISDemo {
11
12
13
14
15
16
17

public static void main(String[] args) throws


IOException {
FileInputStream fis = null;
int available = 0;
int i = 0;
try {
fis = new
FileInputStream("E:/karthi/FIStream1/src/a.txt");
while ((i = fis.read()) != -1) {

18

available = fis.available();

19

char c = (char) i;

20

System.out.print("Available :" +

21 available);
System.out.println(" Read :" + c);

22
23
24

}
} catch (Exception e) {
e.printStackTrace();

25

} finally {

26

if (fis != null) {

27

fis.close();

28

}
}

29
}

30
31

Output
Available :5 Read :K
Available :4 Read :A
Available :3 Read :R
Available :2 Read :T
Available :1 Read :H
Available :0 Read :I

BufferedInputStream example program for skip(long n) in java

/**

program : BufferedInputStream example program for


skip(long n) in java

3
4
5

author

: "candid"

date

: 21.11.12

*/

//java code

import java.io.BufferedInputStream;

import java.io.FileInputStream;

import java.io.FilterInputStream;

10 import java.io.IOException;
11 import java.io.InputStream;
12
13

public class Skip1 {

14

public static void main(String[] args) throws Exception {

15

InputStream is = null;

16

FilterInputStream fis = null;

17

int i = 0;

18

char c;

19

try {

is = new
FileInputStream("F:/karthi/BIStreamSkip/karthi.txt");//
21 karthi.txt

20

// content:karthi

22

fis = new BufferedInputStream(is);

23

while ((i = fis.read()) != -1) {

24

c = (char) i;

25

fis.skip(3);

26

System.out.println("Character read: " + c);

27

28

} catch (IOException e) {

29

e.printStackTrace();

30

} finally {

31

if (is != null)

32

is.close();

33

if (fis != null)

34

fis.close();
}

35
36
}

37
38

Output
Character read: k
Character read: h

BufferedInputStream example program for reset() in java

/**

* @author: candidjava

* @description: in JAVA example program for

*/

5
6
7
8
9

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class BufferedInputStreamDemo {

10

public static void main(String[] args) throws


Exception
{
11

12

InputStream iStream = null;

13

BufferedInputStream bis = null;


try {

14

// read from file c:/test.txt to input

15 stream
16
17

iStream = new
FileInputStream("c:/test.txt");
// input stream converted to buffered input

18 stream
19

bis = new BufferedInputStream(iStream);

20

// read and print characters one by one

21

System.out.println("Char : " + (char)


bis.read());

22

System.out.println("Char : " + (char)

23 bis.read());
24

System.out.println("Char : " + (char)


bis.read());

// mark is set on the input stream


bis.mark(0);

25

System.out.println("Char : " + (char)

26 bis.read());
27

System.out.println("reset() invoked");

28

// reset is called
bis.reset();

29

// read and print characters

30

System.out.println("Char : " + (char)

31 bis.read());
32
33

System.out.println("Char : " + (char)


bis.read());
} catch (Exception e) {

34

e.printStackTrace();

35

} finally {

36
37

// releases any system resources associated


with
the
stream
38
if (iStream != null)

39

iStream.close();

40

if (bis != null)

41

bis.close();

42
}

43
}
}

Output
Char : A
Char : B
Char : C
Char : D
reset() invoked
Char : D
Char : E

Thread Example program for run()

// Thread Example Program for run()

/**

@author: Candidjava.com

@description: This program runs the run() method first


then executes the main method.

*/

6
7

public class New implements Runnable

public void run() // run method starts here

10 {
11 try{
12 for(int i=0;i<11;i++)
13
14
15
16
17
18
19
20

{
System.out.println(i);
Thread.sleep(1000); //waiting for one second
}
}
catch(Exception e){}
}
public static void main(String a[])
{

21 New n=new New(); // creating a new object


22 Thread t1=new Thread(n); // creating a thread object
23 t1.run(); // starting the run method
24 try{

25
26
27
28
29

for(int j=11;j<21;j++)
{
System.out.println(j);
Thread.sleep(1000);
}

30
31
32

}
catch(Exception e){}
}

33 }
34
output:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Java Program used to get the pathname of the file using getPath() method

Get Filepath program to get the pathname of the file.

Example Program
?

package service1;

2
3

import java.io.File;

4
5
6

public class StrFilepath {


public static void main(String[] args) {

7
8
9
10

File f = null;
String v;
boolean bool = false;

11
12

try {
// create new file

13

f = new File("test.txt");

14
15

// pathname string from abstract pathname

16

v = f.getPath();

17
18

// true if the file path exists

19

bool = f.exists();

20
21

// if file exists

22

if (bool) {

23

// prints

24

System.out.print("pathname: " + v);


}

25
26

} catch (Exception e) {
// if any error occurs

27

e.printStackTrace();

28
29

30
}

31
32

33
Output
pathname: test.txt
Description
The java.io.File.getPath() method converts the abstract pathname into pathname string. To separate the names in the name sequence the
resulting string uses the default name-separator character.
Declaration
Following is the declaration for java.io.File.getPath() method:
public String getPath()
Parameters
Not Applicable.
Return Value
The method returns pathname string form of this abstract pathname.
Exception
Not Applicable.

Potrebbero piacerti anche