SlideShare a Scribd company logo
Java IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to
make input and output operation in java. In general, a stream means continuous flow of data.
Streams are clean way to deal with input/output without having every part of your code
understand the physical.
Java encapsulates Stream under java.io package. Java defines two types of streams. They are,
1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.
Java Byte Stream Classes
Byte stream is defined by using two abstract class at the top of hierarchy, they are
InputStream and OutputStream.
These two abstract classes have several concrete classes that handle various devices such as
disk files, network connection etc.
Some important Byte stream classes.
Stream class Description
BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStream Used for Buffered Output Stream.
DataInputStream Contains method for reading java standard datatype
DataOutputStream An output stream that contain method for writing java standard data type
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that write to a file.
InputStream Abstract class that describe stream input.
OutputStream Abstract class that describe stream output.
PrintStream Output Stream that contain print() and println() method
These classes define several key methods. Two most important are
1. read() : reads byte of data.
2. write() : Writes byte of data.
Java Character Stream Classes
Character stream is also defined by using two abstract class at the top of hierarchy, they are
Reader and Writer.
These two abstract classes have several concrete classes that handle unicode character.
Some important Charcter stream classes
Stream class Description
BufferedReader Handles buffered input stream.
BufferedWriter Handles buffered output stream.
FileReader Input stream that reads from file.
FileWriter Output stream that writes to file.
InputStreamReader Input stream that translate byte to character
OutputStreamReader Output stream that translate character to byte.
PrintWriter Output Stream that contain print() and println() method.
Reader Abstract class that define character stream input
Writer Abstract class that define character stream output
Reading Console Input
We use the object of BufferedReader class to take inputs from the keyboard.
Reading Characters
read() method is used with BufferedReader object to read characters. As this function returns
integer type value has we need to use typecasting to convert it into char type.
Below is a simple example explaining character input.
// prg on reading a single character
import java.io.*;
class CharRead
{
public static void main( String args[])
throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Any Character");
char c = (char)br.read(); //Reading character
System.out.println("The Given Char "+c);
}
}
Reading Strings in Java
To read string we have to use readLine() function with BufferedReader class's object.
Program to take String input from Keyboard in Java
// Prg on reading string with BufferedReader
import java.io.*;
class Testing
{
public static void main(String[] args) throws Exception
{
String st;
BufferedReader x = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Any String");
st = x.readLine(); //Reading String
System.out.println("The Given String "+st);
}
}
Program to read from a file using BufferedReader class
import java. Io *;
class ReadTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
fl.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
Program to write to a File using FileWriter class
// Prg on writing to file
import java.io.*;
class WriteTest
{
public static void main(String[] args)
{
try
{
File fl = new File("myfile.txt");
String str="All the best for the Supplementary and Regular Exams";
FileWriter fw = new FileWriter(fl) ;
fw.write(str);
fw.close();
System.out.println("File Successfully Created and Data was written into it");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Java Serialization and Deserialization
Serialization is a process of converting an object into a sequence of bytes which can be
persisted to a disk or database or can be sent through streams. The reverse process of creating
object from sequence of bytes is called deserialization.
A class must implement Serializable interface present in java.io package in order to serialize its
object successfully.
To implement serialization and deserialization, Java provides two classes ObjectOutputStream
and ObjectInputStream.
ObjectOutputStream class
It is used to write object states to the file. An object that implements java.io.Serializable
interface can be written to strams. It provides various methods to perform serialization.
ObjectInputStream class
An ObjectInputStream deserializes objects and primitive data written using an
ObjectOutputStream.
writeObject() and readObject() Methods
The writeObject() method of ObjectOutputStream class serializes an object and send it to the
output stream.
public final void writeObject(object x) throws IOException
The readObject() method of ObjectInputStream class references object out of stream and
deserialize it.
public final Object readObject() throws IOException,ClassNotFoundException
while serializing if you do not want any field to be part of object state then declare it
either static or transient based on your need and it will not be included during java serialization
process.
Example: Serializing an Object in Java
In this example, we have a class that implements Serializable interface to make its object
serialized.
import java.io.*;
class Studentinfo implements Serializable
{
String name;
int rid;
static String contact;
Studentinfo(String n, int r, String c)
{
this.name = n;
this.rid = r;
this.contact = c;
}
}
class Demo
{
public static void main(String[] args)
{
try
{
Studentinfo si = new Studentinfo("Abhi", 104, "110044");
FileOutputStream fos = new FileOutputStream("student.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(si);
oos.flush();
oos.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Object of Studentinfo class is serialized using writeObject() method and written
to student.txt file.
Example : Deserialization of Object in Java
To deserialize the object, we are using ObjectInputStream class that will read the object from
the specified file. See the below example.
import java.io.*;
class Studentinfo implements Serializable
{
String name;
int rid;
static String contact;
Studentinfo(String n, int r, String c)
{
this.name = n;
this.rid = r;
this.contact = c;
}
}
class Demo
{
public static void main(String[] args)
{
Studentinfo si=null ;
try
{
FileInputStream fis = new FileInputStream("/filepath/student.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
si = (Studentinfo)ois.readObject();
}
catch (Exception e)
{
e.printStackTrace(); }
System.out.println(si.name);
System.out. println(si.rid);
System.out.println(si.contact);
}
}
Output
Abhi
104
Null
transient Keyword
While serializing an object, if we don't want certain data member of the object to be serialized
we can mention it transient. transient keyword will prevent that data member from being
serialized.
class studentinfo implements Serializable
{
String name;
transient int rid;
static String contact;
}
 Making a data member transient will prevent its serialization.
 In this example rid will not be serialized because it is transient, and contact will also
remain unserialized because it is static.
RandomAccessFile
This class is used for reading and writing to random access file. A random access file behaves
like a large array of bytes. There is a cursor implied to the array called file pointer, by moving
the cursor we do the read write operations.
RandomAccessFile(File
file, String mode)
Creates a random access file stream to read from, and optionally to
write to, the file specified by the File argument.
Methods
Modifier
and Type
Method Method
void close() It closes this random access file stream and releases
any system resources associated with the stream.
int readInt() It reads a signed 32-bit integer from this file.
void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.
void writeDouble(double
v)
It converts the double argument to a long using the
doubleToLongBits method in class Double, and then
writes that long value to the file as an eight-byte
quantity, high byte first.
void writeFloat(float v) It converts the float argument to an int using the
floatToIntBits method in class Float, and then writes
that int value to the file as a four-byte quantity, high
byte first.
void write(int b) It writes the specified byte to this file.
int read() It reads a byte of data from this file.
long length() It returns the length of this file.
void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.
Example
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample {
static final String FILEPATH ="myFile.TXT";
public static void main(String[] args) {
try {
System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
writeToFile(FILEPATH, "I love my country and my people", 31);
} catch (IOException e) {
e.printStackTrace();
}
}
private static byte[] readFromFile(String filePath, int position, int size)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
file.close();
return bytes;
}
private static void writeToFile(String filePath, String data, int position)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(position);
file.write(data.getBytes());
file.close();
}
}
The myFile.TXT contains text "This class is used for reading and writing to random access file."
after running the program it will contains
I love my country and my people.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
public class Fx_Example2 extends Application
{
public void start(Stage primaryStage)
{
Label label1 = new Label("I love JavaFX!"); //show text
StackPane root = new StackPane(); //create a layout
root.getChildren().add(label1); //add the Label to the layout
Scene scene = new Scene(root,100,100);
primaryStage.setScene(scene); //set the Scene
primaryStage.show(); //show the Stage
}
public static void main(String[] args)
{
launch(args);
}
}
Ad

More Related Content

Similar to Java IO Stream, the introduction to Streams (20)

Java stream
Java streamJava stream
Java stream
Arati Gadgil
 
file handling in object oriented programming through java
file handling in object oriented programming through javafile handling in object oriented programming through java
file handling in object oriented programming through java
Parameshwar Maddela
 
Java I/O
Java I/OJava I/O
Java I/O
Jayant Dalvi
 
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & OutputItp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
phanleson
 
UNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesUNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf Notes
SakkaravarthiS1
 
Java
JavaJava
Java
Dhruv Sabalpara
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3
sotlsoc
 
File Input and Output in Java Programing language
File Input and Output in Java Programing languageFile Input and Output in Java Programing language
File Input and Output in Java Programing language
BurhanKhan774154
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptx
RathanMB
 
Io streams
Io streamsIo streams
Io streams
Elizabeth alexander
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
Victer Paul
 
chapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and streamchapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
CORE JAVA-1
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
Java development development Files lectur6.ppt
Java development development Files lectur6.pptJava development development Files lectur6.ppt
Java development development Files lectur6.ppt
rafeakrafeak
 
IO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon pptIO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
NilaNila16
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
Eduardo Bergavera
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
Vince Vo
 
file handling in object oriented programming through java
file handling in object oriented programming through javafile handling in object oriented programming through java
file handling in object oriented programming through java
Parameshwar Maddela
 
Itp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & OutputItp 120 Chapt 19 2009 Binary Input & Output
Itp 120 Chapt 19 2009 Binary Input & Output
phanleson
 
UNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesUNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf Notes
SakkaravarthiS1
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3
sotlsoc
 
File Input and Output in Java Programing language
File Input and Output in Java Programing languageFile Input and Output in Java Programing language
File Input and Output in Java Programing language
BurhanKhan774154
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptx
RathanMB
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
Victer Paul
 
chapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and streamchapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
Java development development Files lectur6.ppt
Java development development Files lectur6.pptJava development development Files lectur6.ppt
Java development development Files lectur6.ppt
rafeakrafeak
 
IO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon pptIO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
NilaNila16
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
Eduardo Bergavera
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
Vince Vo
 

Recently uploaded (20)

SICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introductionSICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introduction
fabienklr
 
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
Reflections on Morality, Philosophy, and History
 
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
Taqyea
 
Analog electronic circuits with some imp
Analog electronic circuits with some impAnalog electronic circuits with some imp
Analog electronic circuits with some imp
KarthikTG7
 
Machine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATIONMachine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATION
DarrinBright1
 
Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control Monthly May 2025Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
A Survey of Personalized Large Language Models.pptx
A Survey of Personalized Large Language Models.pptxA Survey of Personalized Large Language Models.pptx
A Survey of Personalized Large Language Models.pptx
rutujabhaskarraopati
 
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdfML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
rameshwarchintamani
 
Computer Security Fundamentals Chapter 1
Computer Security Fundamentals Chapter 1Computer Security Fundamentals Chapter 1
Computer Security Fundamentals Chapter 1
remoteaimms
 
Novel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth ControlNovel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth Control
Chris Harding
 
Working with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to ImplementationWorking with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to Implementation
Alabama Transportation Assistance Program
 
Understanding Structural Loads and Load Paths
Understanding Structural Loads and Load PathsUnderstanding Structural Loads and Load Paths
Understanding Structural Loads and Load Paths
University of Kirkuk
 
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
IJCNCJournal
 
DED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedungDED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedung
nabilarizqifadhilah1
 
Autodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User InterfaceAutodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User Interface
Atif Razi
 
introduction technology technology tec.pptx
introduction technology technology tec.pptxintroduction technology technology tec.pptx
introduction technology technology tec.pptx
Iftikhar70
 
NOMA analysis in 5G communication systems
NOMA analysis in 5G communication systemsNOMA analysis in 5G communication systems
NOMA analysis in 5G communication systems
waleedali330654
 
Interfacing PMW3901 Optical Flow Sensor with ESP32
Interfacing PMW3901 Optical Flow Sensor with ESP32Interfacing PMW3901 Optical Flow Sensor with ESP32
Interfacing PMW3901 Optical Flow Sensor with ESP32
CircuitDigest
 
C_Dayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy 3.pdf
C_Dayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy 3.pdfC_Dayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy 3.pdf
C_Dayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy 3.pdf
amanpathak160605
 
SICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introductionSICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introduction
fabienklr
 
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
Taqyea
 
Analog electronic circuits with some imp
Analog electronic circuits with some impAnalog electronic circuits with some imp
Analog electronic circuits with some imp
KarthikTG7
 
Machine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATIONMachine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATION
DarrinBright1
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
A Survey of Personalized Large Language Models.pptx
A Survey of Personalized Large Language Models.pptxA Survey of Personalized Large Language Models.pptx
A Survey of Personalized Large Language Models.pptx
rutujabhaskarraopati
 
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdfML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
ML_Unit_V_RDC_ASSOCIATION AND DIMENSIONALITY REDUCTION.pdf
rameshwarchintamani
 
Computer Security Fundamentals Chapter 1
Computer Security Fundamentals Chapter 1Computer Security Fundamentals Chapter 1
Computer Security Fundamentals Chapter 1
remoteaimms
 
Novel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth ControlNovel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth Control
Chris Harding
 
Understanding Structural Loads and Load Paths
Understanding Structural Loads and Load PathsUnderstanding Structural Loads and Load Paths
Understanding Structural Loads and Load Paths
University of Kirkuk
 
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
Efficient Algorithms for Isogeny Computation on Hyperelliptic Curves: Their A...
IJCNCJournal
 
DED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedungDED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedung
nabilarizqifadhilah1
 
Autodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User InterfaceAutodesk Fusion 2025 Tutorial: User Interface
Autodesk Fusion 2025 Tutorial: User Interface
Atif Razi
 
introduction technology technology tec.pptx
introduction technology technology tec.pptxintroduction technology technology tec.pptx
introduction technology technology tec.pptx
Iftikhar70
 
NOMA analysis in 5G communication systems
NOMA analysis in 5G communication systemsNOMA analysis in 5G communication systems
NOMA analysis in 5G communication systems
waleedali330654
 
Interfacing PMW3901 Optical Flow Sensor with ESP32
Interfacing PMW3901 Optical Flow Sensor with ESP32Interfacing PMW3901 Optical Flow Sensor with ESP32
Interfacing PMW3901 Optical Flow Sensor with ESP32
CircuitDigest
 
C_Dayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy 3.pdf
C_Dayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy 3.pdfC_Dayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy 3.pdf
C_Dayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy 3.pdf
amanpathak160605
 
Ad

Java IO Stream, the introduction to Streams

  • 1. Java IO Stream Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to make input and output operation in java. In general, a stream means continuous flow of data. Streams are clean way to deal with input/output without having every part of your code understand the physical. Java encapsulates Stream under java.io package. Java defines two types of streams. They are, 1. Byte Stream : It provides a convenient means for handling input and output of byte. 2. Character Stream : It provides a convenient means for handling input and output of characters. Character stream uses Unicode and therefore can be internationalized. Java Byte Stream Classes Byte stream is defined by using two abstract class at the top of hierarchy, they are InputStream and OutputStream. These two abstract classes have several concrete classes that handle various devices such as disk files, network connection etc. Some important Byte stream classes. Stream class Description BufferedInputStream Used for Buffered Input Stream.
  • 2. BufferedOutputStream Used for Buffered Output Stream. DataInputStream Contains method for reading java standard datatype DataOutputStream An output stream that contain method for writing java standard data type FileInputStream Input stream that reads from a file FileOutputStream Output stream that write to a file. InputStream Abstract class that describe stream input. OutputStream Abstract class that describe stream output. PrintStream Output Stream that contain print() and println() method These classes define several key methods. Two most important are 1. read() : reads byte of data. 2. write() : Writes byte of data. Java Character Stream Classes Character stream is also defined by using two abstract class at the top of hierarchy, they are Reader and Writer.
  • 3. These two abstract classes have several concrete classes that handle unicode character. Some important Charcter stream classes Stream class Description BufferedReader Handles buffered input stream. BufferedWriter Handles buffered output stream. FileReader Input stream that reads from file. FileWriter Output stream that writes to file. InputStreamReader Input stream that translate byte to character
  • 4. OutputStreamReader Output stream that translate character to byte. PrintWriter Output Stream that contain print() and println() method. Reader Abstract class that define character stream input Writer Abstract class that define character stream output Reading Console Input We use the object of BufferedReader class to take inputs from the keyboard. Reading Characters read() method is used with BufferedReader object to read characters. As this function returns integer type value has we need to use typecasting to convert it into char type. Below is a simple example explaining character input.
  • 5. // prg on reading a single character import java.io.*; class CharRead { public static void main( String args[]) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Any Character"); char c = (char)br.read(); //Reading character System.out.println("The Given Char "+c); } } Reading Strings in Java To read string we have to use readLine() function with BufferedReader class's object. Program to take String input from Keyboard in Java // Prg on reading string with BufferedReader import java.io.*; class Testing { public static void main(String[] args) throws Exception { String st;
  • 6. BufferedReader x = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Any String"); st = x.readLine(); //Reading String System.out.println("The Given String "+st); } } Program to read from a file using BufferedReader class import java. Io *; class ReadTest { public static void main(String[] args) { try { File fl = new File("d:/myfile.txt"); BufferedReader br = new BufferedReader(new FileReader(fl)) ; String str; while ((str=br.readLine())!=null) { System.out.println(str); } br.close(); fl.close(); }
  • 7. catch(IOException e) { e.printStackTrace(); } } } Program to write to a File using FileWriter class // Prg on writing to file import java.io.*; class WriteTest { public static void main(String[] args) { try { File fl = new File("myfile.txt"); String str="All the best for the Supplementary and Regular Exams"; FileWriter fw = new FileWriter(fl) ; fw.write(str); fw.close(); System.out.println("File Successfully Created and Data was written into it"); } catch (IOException e) {
  • 8. e.printStackTrace(); } } } Java Serialization and Deserialization Serialization is a process of converting an object into a sequence of bytes which can be persisted to a disk or database or can be sent through streams. The reverse process of creating object from sequence of bytes is called deserialization. A class must implement Serializable interface present in java.io package in order to serialize its object successfully. To implement serialization and deserialization, Java provides two classes ObjectOutputStream and ObjectInputStream. ObjectOutputStream class It is used to write object states to the file. An object that implements java.io.Serializable interface can be written to strams. It provides various methods to perform serialization. ObjectInputStream class An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream. writeObject() and readObject() Methods The writeObject() method of ObjectOutputStream class serializes an object and send it to the output stream. public final void writeObject(object x) throws IOException The readObject() method of ObjectInputStream class references object out of stream and deserialize it. public final Object readObject() throws IOException,ClassNotFoundException
  • 9. while serializing if you do not want any field to be part of object state then declare it either static or transient based on your need and it will not be included during java serialization process. Example: Serializing an Object in Java In this example, we have a class that implements Serializable interface to make its object serialized. import java.io.*; class Studentinfo implements Serializable { String name; int rid; static String contact; Studentinfo(String n, int r, String c) { this.name = n; this.rid = r; this.contact = c; } } class Demo { public static void main(String[] args) { try
  • 10. { Studentinfo si = new Studentinfo("Abhi", 104, "110044"); FileOutputStream fos = new FileOutputStream("student.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(si); oos.flush(); oos.close(); } catch (Exception e) { System.out.println(e); } } } Object of Studentinfo class is serialized using writeObject() method and written to student.txt file. Example : Deserialization of Object in Java To deserialize the object, we are using ObjectInputStream class that will read the object from the specified file. See the below example. import java.io.*; class Studentinfo implements Serializable { String name; int rid; static String contact;
  • 11. Studentinfo(String n, int r, String c) { this.name = n; this.rid = r; this.contact = c; } } class Demo { public static void main(String[] args) { Studentinfo si=null ; try { FileInputStream fis = new FileInputStream("/filepath/student.txt"); ObjectInputStream ois = new ObjectInputStream(fis); si = (Studentinfo)ois.readObject(); } catch (Exception e) { e.printStackTrace(); } System.out.println(si.name); System.out. println(si.rid); System.out.println(si.contact);
  • 12. } } Output Abhi 104 Null transient Keyword While serializing an object, if we don't want certain data member of the object to be serialized we can mention it transient. transient keyword will prevent that data member from being serialized. class studentinfo implements Serializable { String name; transient int rid; static String contact; }  Making a data member transient will prevent its serialization.  In this example rid will not be serialized because it is transient, and contact will also remain unserialized because it is static. RandomAccessFile
  • 13. This class is used for reading and writing to random access file. A random access file behaves like a large array of bytes. There is a cursor implied to the array called file pointer, by moving the cursor we do the read write operations. RandomAccessFile(File file, String mode) Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument. Methods Modifier and Type Method Method void close() It closes this random access file stream and releases any system resources associated with the stream. int readInt() It reads a signed 32-bit integer from this file. void seek(long pos) It sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs. void writeDouble(double v) It converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the file as an eight-byte quantity, high byte first.
  • 14. void writeFloat(float v) It converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the file as a four-byte quantity, high byte first. void write(int b) It writes the specified byte to this file. int read() It reads a byte of data from this file. long length() It returns the length of this file. void seek(long pos) It sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs. Example import java.io.IOException; import java.io.RandomAccessFile; public class RandomAccessFileExample { static final String FILEPATH ="myFile.TXT"; public static void main(String[] args) { try { System.out.println(new String(readFromFile(FILEPATH, 0, 18))); writeToFile(FILEPATH, "I love my country and my people", 31); } catch (IOException e) { e.printStackTrace();
  • 15. } } private static byte[] readFromFile(String filePath, int position, int size) throws IOException { RandomAccessFile file = new RandomAccessFile(filePath, "r"); file.seek(position); byte[] bytes = new byte[size]; file.read(bytes); file.close(); return bytes; } private static void writeToFile(String filePath, String data, int position) throws IOException { RandomAccessFile file = new RandomAccessFile(filePath, "rw"); file.seek(position); file.write(data.getBytes()); file.close(); } } The myFile.TXT contains text "This class is used for reading and writing to random access file." after running the program it will contains I love my country and my people.
  • 16. import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.*; import javafx.scene.layout.*; import javafx.scene.control.*; public class Fx_Example2 extends Application { public void start(Stage primaryStage) { Label label1 = new Label("I love JavaFX!"); //show text StackPane root = new StackPane(); //create a layout root.getChildren().add(label1); //add the Label to the layout Scene scene = new Scene(root,100,100); primaryStage.setScene(scene); //set the Scene primaryStage.show(); //show the Stage } public static void main(String[] args) { launch(args); } }
  翻译: