Saturday, June 30, 2018

File class assignment

import java.io.File;
import java.util.Scanner;

public class TheFileClassAssignment
{
public static void main(String[] args)
{
// create object of scanner to get data from keyboard
Scanner sc = new Scanner(System.in);

System.out.println("Enter a path: ");
String path = sc.nextLine();

// denote the path using file class
File f = new File(path);

// take some string variables to store some data
String javaFileNames = "", mpegFileNames = "", jpegFileNames = "",
txtFileNames = "";

// take some int variables to store number of files
int javaFiles = 0, mpegFiles = 0, jpegFiles = 0,
txtFiles = 0;

// fetch list of all the resources from the path
File[] fa = f.listFiles();

// fetch data (bole to resources of path) from the array using for loop
for (int i = 0; i < fa.length; i++)
{
// check if resource is a file
// if isFile() method returns true then resource is a file (remember..)
if(fa[i].isFile())
{
// fetch the file name from the i'th element of array
String fileName = fa[i].getName();

// check the extension of files using endsWith() method of string class

if(fileName.endsWith(".java")) // means its a java file
{
// concatenate the fileName in javaFileNames and also a new line
javaFileNames = javaFileNames + fileName + "\n";

// increment the counter for java files
javaFiles++;
}

else if(fileName.endsWith(".txt")) // means its a text file
{
// concatenate the fileName in txtFileNames and also a new line
txtFileNames = ">> " +txtFileNames + fileName + "\n";

// increment the counter for text files
txtFiles++;
}

else if(fileName.endsWith(".jpeg")
|| fileName.endsWith(".jpg")) // means its a image file
{
// concatenate the fileName in jpegFileNames and also a new line
jpegFileNames = jpegFileNames + fileName + "\n";

// increment the counter for image files
jpegFiles++;
}

else if(fileName.endsWith(".mpeg")
|| fileName.endsWith(".mpg")) // means its a movie file
{
// concatenate the fileName in mpegFileNames and also a new line
mpegFileNames = ">> " +mpegFileNames + fileName + "\n";

// increment the counter for movie files
mpegFiles++;
}

} // end of if

} // end of for loop

System.out.println("# Report of path "+path+" is given below #");

System.out.println("\njava files ->");
System.out.print(javaFileNames);
System.out.println("** Total java file are "+javaFiles+" **");

System.out.println("\ntext files ->");
System.out.print(txtFileNames);
System.out.println("** Total text file are "+txtFiles);

System.out.println("\njpeg or jpg files ->");
System.out.print(jpegFileNames);
System.out.println("** Total jpeg file are "+jpegFiles+" **");

System.out.println("\nmpeg or mpg files ->");
System.out.print(mpegFileNames);
System.out.println("** Total mpeg file are "+mpegFiles+" **");

// calculate total number of files in this path
int totalFiles = javaFiles + txtFiles + jpegFiles + mpegFiles;

System.out.println("\n**Total files in this path are "+totalFiles+" **");

} // end of main method

} // end of class

Friday, June 29, 2018

A great JDBC API the ResultSetMetaData interface

### ResultSetMetaData ###

It is an interface, and its is a part of JDBC API. 
This interface is one of the most useful interface of JDBC API.

# Objective # 


By using this interface we can provide a Metadata about ResultSet. 
Metadata means the data about data.

# For example #

ResultSet keeps the data of table whereas the ResultSetMeta keeps the information about ResultSet.

Real life example: If Person is a ResultSet then the biography of Person is a ResultSetMeta.


How to get the object of ResultSetMeta:


the syntax => ResultSetMeta refvar = objectOfResultSet.getMetaData();


here, getMetaData() is a method of ResultSet, that returns object of ResultSetMeta.


# Methods of ResultSetMeta #


1. int getColumnCount() -> This method will return number of columns available inside ResultSet.


2. String getColumnName(int indexOfColumn) -> This method will return the name of column available at given index


3. String getColumnTypeName(int indexOfColumn) -> This method will return the type of column available at given index


Note: in method 2 and 3 the indexOfColumn must be >= 1 and < number of columns in ResultSet. 




# First program to show the application of ResultSetMetaData #

note: save this code inside FirstApplicationOfResultSetMetaData.java file

import java.sql.*;
import java.util.Scanner;
public class FirstApplicationOfResultSetMetaData
{
public static void main(String[] args)
{
try
{
// lets create object of sccaner class to get input from keyboard
Scanner sc = new Scanner(System.in);

System.out.print("Enter the name of database: ");
  // get name of database from the keyboard
String dbName = sc.nextLine();

System.out.print("Enter the name of the table: ");
// get name of table from the keyboard
  String tableName = sc.nextLine();

// lets load the driver class for MySQL server database
Class.forName("com.mysql.jdbc.Driver");

// lets get object of connection to communicate with database
// note: co is the object name of connection
Connection co = DriverManager.getConnection
("jdbc:mysql://localhost:3306/"+dbName, "root","root");

// lets get object of statement to make a dialog with database
// note: st is the object name of statement
Statement st = co.createStatement();

// lets execute the select query
// note: rs is the object of resultset, which will keep the data of table
// note: here i have prefixed the name of database than dot (bole toh .)
// than the name of table
ResultSet rs = st.executeQuery("select * from "+dbName+"."+tableName);

// lets get object of resultsetmetadata to know about resultset
// note: rsmd is the object of resultsetmetadata
ResultSetMetaData rsmd = rs.getMetaData();

// lets get number of columns inside the resultset
int columns = rsmd.getColumnCount();

System.out.println("# No of columns inside ResultSet are "
+columns+" #");

// create a loop from 1 to number of columns inside resultset
System.out.println("# Structure of data inside "
+ "resultset is given below #");

for(int i = 1; i <= columns; i++)
{
// lets get the name of column of resultset which is available
// at given index
String columnName = rsmd.getColumnName(i);

// lets get the type of column of resultset which is available
// at given index
String columnType = rsmd.getColumnTypeName(i);

// show the index of column, its name, and its type
System.out.println("Index: "+i+", Name: "+columnName
+", Type: "+columnType);
}

// lets close the connection
co.close();

}
// any runtime error (bole toh exception) will be handled by the catch block
// e is the object of exception class
catch (Exception e)
{
System.out.println("Runtime error is "+e);
}

}
}

# First program to ends here #

# # # # # # # # # # # # # # # # # # 

# Second program to show the application of ResultSetMetaData #

note: save this code inside SecondApplicationOfResultSetMetaData.java file

import java.io.FileOutputStream;
import java.sql.*;
import java.util.Scanner;
public class SecondApplicationOfResultSetMetaData
{
public static void main(String[] args)
{
try
{
//  create object of scanner class to get input from keyboard
Scanner sc = new Scanner(System.in);

System.out.print("Enter the name of database: ");
String dbName = sc.nextLine();

System.out.print("Enter the name of the table: ");
String tableName = sc.nextLine();

//  load the driver class for MySQL server database
Class.forName("com.mysql.jdbc.Driver");

//  get object of connection to communicate with database
// note: co is the object name of connection
Connection co = DriverManager.getConnection
("jdbc:mysql://localhost:3306/"+dbName, "root","root");

//  get object of statement to make a dialog with database
// note: st is the object name of statement
Statement st = co.createStatement();

//  execute the select query
// note: rs is the object of resultset, which will keep the data of table
// note: here i have prefixed the name of database than dot (bole toh .)
// than the name of table
ResultSet rs = st.executeQuery("select * from "+dbName+"."+tableName);

//  get object of resultsetmetadata to know about resultset
// note: rsmd is the object of resultsetmetadata
ResultSetMetaData rsmd = rs.getMetaData();

//  get number of columns inside the resultset
int columns = rsmd.getColumnCount();

// in this string we will create html code
String result = "";

result = "<html>"
+ "<head>"
+ "<title>"
+ dbName+"_"+tableName
+ "</title>"
+ "</head>"
+ "<body>"
+ "<center>"
+ "<h3 style='color : red'>[dbname: "+dbName+"]</h3>"
+ "<h3 style='color : blue'>[tablename: "+tableName+"]</h3>"
// create html table
+ "<table border=1>";

for(int i = 1; i <= columns; i++)
{
String columnName = rsmd.getColumnName(i);

// concatenate the column-name in result along with some html
// th means table heading
result = result + "<th>" + columnName + "</th>";
}

// fetch a record from the result-set
while(rs.next())
{
// create a row in html table
// tr means table row
result = result + "<tr>";

// using this loop we will fetch all the columns of the record
// which was fetched by the rs.next() method
for(int i = 1; i <= columns; i++)
{
// get column name in result-set
String columnName = rsmd.getColumnName(i);

// fetch data of column from the result-set using column-name
String columnData = rs.getString(columnName);

// store the data of column inside the column in html table
// td means table-data
result = result +"<td>" +  columnData + "</td>";
}

// combine a row after each record
result = result + "<tr>";
}

// complete the table
result = result + "</table>"
+ "</body>"
// complte the html code
+ "</html>";

// directory to store a file
String directory = "C:\\Users\\admin\\Desktop\\";

// to store filename
String filename = dbName+"_"+tableName+".html";

// to store complete filepath
String filepath = directory + filename;

//  open a file in write mode
// this file will be created inside "C:\Users\admin\Desktop" location
// of our computer
FileOutputStream fo = new FileOutputStream
(filepath,false);

//  convert the string into array of byte
byte[] array = result.getBytes();

//  store the data of array inside the file in one go
fo.write(array);

//  show the message on console (bole toh eclipse console)
System.out.println("Please check "+dbName+"_"
+tableName+".html file"+ " in "
+directory+" location");

//  close the file
fo.close();

//  close the connection
co.close();

}
// runtime error (bole toh exception) will be handled by catch block
// here e is the object of exception class
catch (Exception e)
{
System.out.println("Runtime error is "+e);
}

}
}

# Second program ends here #

Thursday, June 28, 2018

2 to 4 batch : 28 - JUNE - 2018

import java.io.File;
import java.util.Date;
import java.util.Scanner;

public class TheFileClass01
{
public static void main(String[] args)
{
// create object of scanner class to get input from keyboard
Scanner sc = new Scanner(System.in);

System.out.print("Input a path: ");
String path = sc.nextLine();

// create object of file class to denote this path
File f = new File(path);

// check if path is correct
if (f.exists())
{
System.out.println("path is correct");

// check if path is of file
if (f.isFile())
{
System.out.println("it is a file");

// get size of file
long filesize = f.length();

System.out.println("size of file is " + filesize + " bytes");

// get last modification time of file
long time = f.lastModified();

// convert milliseconds into actual date and time
Date date = new Date(time);
System.out.println("file modified at " + date);
}

// check if path is of a directory
if (f.isDirectory())
{
System.out.println("it is a directory");
}
} // end of outer if block

// this else will be executed if path is not correct
else
{
System.out.println("path is not correct");
}

}
}

# # # # # # # # # # # # # # # # # # # #

import java.io.File;
import java.util.Date;
import java.util.Scanner;

public class TheFileClass02
{
public static void main(String[] args)
{
// create object of scanner class to get input from keyboard
Scanner sc = new Scanner(System.in);

System.out.print("Input a path: ");
String path = sc.nextLine();

// create object of file class to denote this path
File f = new File(path);

// lets create a directory inside this path
if(f.mkdir())
{
System.out.println("directory created");
}
else
{
System.out.println("directory already exists");
}

}
}

# # # # # # # # # # # # # # # # # # # #

import java.io.File;
import java.util.Date;
import java.util.Scanner;

public class TheFileClass03
{
public static void main(String[] args)
{
// create object of scanner class to get input from keyboard
Scanner sc = new Scanner(System.in);

System.out.print("Input a path: ");
String path = sc.nextLine();

// create object of file class to denote this path
File f = new File(path);

// delete a resource inside this path (in order to delete
// a directory it must be empty)
if(f.delete())
{
System.out.println("resource deleted");
}
// else will be executed if resource is not deleted
else
{
System.out.println("resource cant be deleted");
}

}
}


# # # # # # # # # # # # # # # # # # # #

import java.io.File;
import java.util.Date;
import java.util.Scanner;

public class TheFileClass04 
{
public static void main(String[] args) 
{
// create object of scanner class to get input from keyboard
Scanner sc = new Scanner(System.in);

System.out.print("Input a path that need to be renamed: ");
String oldPath = sc.nextLine();

System.out.print("Input a new name: ");
String newPath = sc.nextLine();

// create object of file class to denote old path
File file1 = new File(oldPath);

// create object of file class to denote new path
File file2 = new File(oldPath);
// lets rename oldPath name into new one
if(file1.renameTo(file2))
{
System.out.println("renaming done");
}
// else will be executed if renaming not done
else
{
System.out.println("error in renaming");
}
}
}

# # # # # # # # # # # # # # # # # # # #

import java.io.File;
import java.util.Scanner;

public class TheFileClass05 
{
public static void main(String[] args) 
{
// create object of scanner class to get input from keyboard
Scanner sc = new Scanner(System.in);
System.out.print("Input a path: ");
String path = sc.nextLine();
// create object of file class to denote this path
File f = new File(path);
// lets get the name of resource (file or directory)
String name = f.getName();
System.out.println("name of resource is "+name);
// lets get the name of parent directory of resource
String parent = f.getParent();
System.out.println("parent is "+parent);
}
}

# # # # # # # # # # # # # # # # # # # #

import java.io.File;
import java.util.Date;
import java.util.Scanner;

public class TheFileClass06 
{
public static void main(String[] args) 
{
// create object of scanner class to get input from keyboard
Scanner sc = new Scanner(System.in);
System.out.print("Input a path: ");
String path = sc.nextLine();
// create object of file class to denote this path
File f = new File(path);
// lets get a list of all the resources (files and sub-directories) 
// inside this path
File[] fa = f.listFiles();
// fetch data from this array
for (int i = 0; i < fa.length; i++) 
{
// lets get the name of resource
String name = fa[i].getName();
System.out.print(name);
// check if resource is a file
if(fa[i].isFile())
{
System.out.print(", file");
}

// check if resource is a directory
if(fa[i].isDirectory())
{
System.out.print(", directory");
}
// check if resource is a hidden resource
if(fa[i].isHidden())
{
System.out.print(" << its a hidden resource");
}
// print a blank line
System.out.println();

} // end of loop
}
}

4 to 6 : 27 - JUNE - 2018 : jsp notes

note: create a dynamic web project in eclipse.

# this is index.jsp #

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="signup.html">new user click here</a>
<hr>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="tadak.jsp" method="post">

<fieldset>

<legend>the world of facts</legend>

<input type="radio" name="choice" value="i">
include
<br>
<input type="radio" name="choice" value="f">
forward
<br>
<input type="radio" name="choice" value="r">
redirection
<br>


<input type="submit" value="test all">

</fieldset>

</form>
</body>
</html>
</body>
</html>

================================
# this is signup.html #

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="signup-handler.jsp" method="post">

<fieldset>

<legend>signup</legend>

name
<br>
<input type="text" name="username" required>
<br>

password
<br>
<input type="password" name="password" required>
<br>

email
<br>
<input type="email" name="email" required>
<br>

mobile
<br>
<input type="text" name="mobile" required>
<br>


<input type="submit" value="signup">

</fieldset>

</form>
</body>
</html>

================================
# this is signup-handler.jsp #

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<%--import a package in jsp --%>
<%@ page import="java.sql.*" %>

<%-- specify the name of jsp that will handle
the exception for this jsp --%>
<%@ page errorPage="error-handler.jsp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 
<%-- jsp comment --%>
 
<!-- html comment -->

<%
// comment for scriptlet tags
// fetch the data of html form
String un = request.getParameter("username");
String ps = request.getParameter("password");
String em = request.getParameter("email");
String mo = request.getParameter("mobile");
// load driver class
Class.forName("com.mysql.jdbc.Driver");
// get connection
Connection co = DriverManager.getConnection
("jdbc:mysql://localhost:3306/june_27",
"root","root");
// get statement
Statement st = co.createStatement();
// execute sql statement
st.executeUpdate
("insert into user values('"+un+"','"+ps+"','"
+em+"','"+mo+"')");
// close connection
co.close();
%>
<script type="text/javascript">
alert("data has been saved");
</script>
<a href="index.jsp">goto home page</a>
</body>
</html>

================================
# this is tadak.jsp #

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
// fetch html form data
String ch = request.getParameter("choice");

if(ch.equals("i"))
{
%>
<jsp:include page="bhadak.jsp"/>
<%
}
else if(ch.equals("f"))
{
%>
<jsp:forward page="bhadak.jsp"/>
<% 
}
else
{
System.out.println("i am else");
response.sendRedirect
("http://localhost:8080/apne-paraye/signup.html");
}
%>
<img src="k.jpg" height="150" width="150">
</body>
</html>

================================
# this is bhadak.jsp #

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<img src="t.jpg" height="150" width="150">
</body>
</html>

================================
# this is error-hanlder.jsp #

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<%@ page isErrorPage="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<i>
something went wrong 
</i>
<hr>
<img src="k.jpg" width="200" height="200">
<hr>
<a href="signup.html">retry to signup</a>
</body>
</html>

12 to 2 batch : 28 - JUNE - 2018


public class TimeCheck01
{
public static void main(String[] args)
{
// get the time in milliseconds from 1 - 1 - 1970
// midnight till this time
long t = System.currentTimeMillis();

// show time in milliseconds
System.out.println("milliseconds: "+t);

// show time in seconds
System.out.println("seconds: "+t / 1000);

// show time in hours
System.out.println("hours: "+t / 1000 / 3600);

// show time in days
System.out.println("days: "+t / 1000 / 3600 / 24);

// show time in years
System.out.println("years: "+t / 1000 / 3600 / 24 / 365);
}
}

=============================
import java.util.Scanner;

public class ApplicationOfCurrentTimeMillisMethod
{
public static void main(String[] args) 
{

Scanner sc = new Scanner(System.in);
System.out.print("Enter your full name: ");
                // get current time in milliseconds
long x = System.currentTimeMillis();
                // get string with spaces from the keyboard
String text = sc.nextLine();
                // get current time in milliseconds again
long y = System.currentTimeMillis();
                // get total time taken by the user to input his / her name
long z = y - x;
                
                // convert time in milliseconds to seconds 
                z = z / 1000;
System.out.println("Time taken by user to input his /her name is "+z);
}
}
=============================

Note: This code is to explain the concept of constructor

public class Pen 
{
// these are non static data members (variables)
String type;
int cost;
// this is a user defined no argument constructor
Pen()
{
// initialization of non static data members
type = "ball";
cost = 10;
}
// this is a user defined parameterized constructor
Pen(String type,int cost)
{
// this.type means non static variable
// simple type means local variable 
this.type = type;
this.cost = cost;
}
// this is a non static method to show the data of pen
void showPenData()
{
System.out.println(type+":"+cost);
}
// this an entry point of java application (hamara pyara and dulara main method)
public static void main(String[] args) 
{
// lets create object of pen using no argument constructor
Pen p1 = new Pen();
// lets call the method to show the data of object p1
p1.showPenData();
// lets create object of pen using parameterized constructor
Pen p2 = new Pen("ball",20);
// lets call the method to show the data of object p2
p2.showPenData();
}
}

=============================

import java.util.Date;

public class DemoOfDateClass 
{
public static void main(String[] args) 
{
// lets create object of date class to denote the data and time
Date d = new Date();
// print object-name of date class
System.out.println(d);
}
}

4 to 6 : 27 - JUNE - 2018 : hibernate

* hibernate.properties file *

# dialect : for this DB hibernate will generate sql
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

# db's driver class
hibernate.connection.driver_class=com.mysql.jdbc.Driver

# db's url
hibernate.connection.url=jdbc:mysql://localhost:3306/june26

# db's username and password
hibernate.connection.username=root
hibernate.connection.password=root

# hey hibernate please create tables for me automatically
hibernate.hbm2ddl.auto=update

# hibernate please show the sql that you produce
hibernate.show_sql=true

# hibernate please show the sql in a good format
hibernate.format_sql=true

============================
package beans;

public class Person 
{
// private data members
private int id;
private String name, city;
private int age;

// setters and getters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
System.out.println("lage loo");
this.city = city;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

public Person() {
System.out.println("object of person created");
}
}
============================
* Person.hbm.xml file *

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

   <hibernate-mapping package="beans">
   
    <class name="Person" table="person_info">
    <id name="id" column="person_id">
    <generator class="assigned">
    </generator>
    </id>
    <property name="name" column="person_name"></property>
    <property name="age" column="person_age"></property>
    <property name="city" column="person_city"></property>
    </class>
   

   </hibernate-mapping>
============================
package beans;

import java.util.Scanner;

import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

public class FetchSingleObject 
{
public static void main(String[] args) 
{
Session session = new Configuration().
addResource("Person.hbm.xml").buildSessionFactory()
.openSession();

Scanner sc = new Scanner(System.in);

System.out.print("Input person id: ");
int pId = sc.nextInt();

// fetch an object of person 
Person p = session.get(Person.class, pId);

// check for null object
if(p != null)
{
// fetch data from p using getters
System.out.println(p.getName()+":"+p.getAge()
+":"+p.getCity());
}
else
{
System.out.println("invalid id");
}

// close session
session.close();
}

}
============================
package beans;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

public class FetchListOfObjects 
{
public static void main(String[] args) 
{
Session session = new Configuration().
addResource("Person.hbm.xml").buildSessionFactory()
.openSession();

// get object of query
Query query = session.createQuery("from Person where id >= 2");

// get a list of all the persons from the table
List<Person> listOfPersons = query.list();

// get object from list using for each loop
for(Person p : listOfPersons)
{
// fetch data from p using getters
System.out.println(p.getName()+":"+p.getAge()
+":"+p.getCity());
}

// close session
session.close();
}

}
============================

Wednesday, June 27, 2018

The File IO

# # # # # # # # # # # # # # # # # # 

First program to understand FileInputStream class -: 

import java.io.FileInputStream;

public class DemoOfFileInputStreamPartOne
{
public static void main(String[] args)
{
try
{
  // create object of scanner to get input from keyboard
   Scanner sc = new Scanner(System.in);

   System.out.print("Enter a the name of file with path to open in read mode: ");
String filepath = sc.nextLine();

// open this file in read mode
FileInputStream fi = new FileInputStream
(filepath);

// start an inifinite loop
while(true)
{
// fetch a byte from file and store it
int var = fi.read();

// check for end of the data
if(var == -1)
{
break; // go out of loop
}

// convert the byte into the ASCII char and store
char ch = (char)var;

System.out.print(ch);
}

// close the file
fi.close();

}
catch(Exception e)
{
System.out.println("error "+e);
}
}
}

# # # # # # # # # # # # # # # # # #

Second program to understand FileInputStream class -: 

import java.io.FileInputStream;

public class DemoOfFileInputStreamPartTwo 
{
public static void main(String[] args) 
{
try
{
  // create object of scanner to get input from keyboard
   Scanner sc = new Scanner(System.in);

   System.out.print("Enter a the name of file with path to open in read mode: ");
String filepath = sc.nextLine();
// open this file in read mode
FileInputStream fi = new FileInputStream(filepath);

// get no of bytes those can be read by the read() method
int size = fi.available();
// create an array of byte to store the data of file
byte[] array = new byte[size];
// fetch file data and store it inside this array
fi.read(array);

// convert array of byte into string
String str = new String(array);
System.out.println(str);
// close the file
fi.close();
}
catch(Exception e)
{
System.out.println("error "+e);
}
}
}

# # # # # # # # # # # # # # # # # #

First program to understand FileOutputStream class -: 

import java.io.FileOutputStream;

public class DemoOfFileOutputStreamPartOne 
{
public static void main(String[] args) 
{
try 
{
  // create object of scanner to get input from keyboard
   Scanner sc = new Scanner(System.in);

   System.out.print("Enter a the name of file with path to open in write mode: ");
String filepath1 = sc.nextLine();

   System.out.print("Enter a the name of file with path to open in append mode: ");
String filepath2 = sc.nextLine();

// open a file in write mode
FileOutputStream fo1 = new FileOutputStream(filepath1,false);

// open a file in append mode
FileOutputStream fo2 = new FileOutputStream
(filepath2,true);
System.out.println("files has been created");

  // close the files
fo1.close();
fo2.close();
catch (Exception e) 
{
System.out.println("error "+e);
}
}
}

# # # # # # # # # # # # # # # # # #

Second program to understand FileOutputStream class -: 

import java.io.FileOutputStream;

public class DemoOfFileOutputStreamPartTwo
{
public static void main(String[] args) 
{
try 
{
  // create object of scanner to get input from keyboard
   Scanner sc = new Scanner(System.in);

   System.out.print("Enter a the name of file with path to open in write mode: ");
String filepath = sc.nextLine();
   System.out.print("Enter the data to be stored inside the file: ");
String filedata = sc.nextLine();
// open a file in write mode
FileOutputStream fo = new FileOutputStream
(filepath,false);
// convert string into array of byte and store 
byte[] array = text.getBytes();
// fetch the data of array using for loop
for (int i = 0; i < array.length; i++) 
{
// store the data of ith element of array inside file
fo.write(array[i]);
}
// close the file
fo.close();
catch (Exception e) 
{
System.out.println("error "+e);
}
}
}

# # # # # # # # # # # # # # # # # #

Third program to understand FileOutputStream class -: 

import java.io.FileOutputStream;

public class DemoOfFileOutputStreamPartThree
{
public static void main(String[] args) 
{
try 
{

   // create object of scanner to get input from keyboard
   Scanner sc = new Scanner(System.in);

   System.out.print("Enter a the name of file with path to open in read mode: ");
String filepath = sc.nextLine();
// open  file in write mode
FileOutputStream fo = new FileOutputStream(filepath,false);
// convert string into array of byte and store 
byte[] array = text.getBytes();

// store the data of file inside the array in one go (matlab ek baar mai)
fo.write(array);
// close the file
fo.close();
catch (Exception e) 
{
System.out.println("error "+e);
}
}
}
# # # # # # # # # # # # # # # # # #