SlideShare a Scribd company logo
1 of 36
File I/O
File Input and Output Operations:-
 File I/O operations are performed using the concept of streams.
 A stream means a continuous flow of data.
 A stream is a logical container of data that allows us to read from and
write to it.
 The stream-based IO operations are faster than normal IO operations
Functionality of java streams
 Every Java program creates 3 streams automatically.
 These streams are attached to the console
1. System.out: standard output stream for console output operations.
2. System.in: standard input stream for console input operations.
3. System.err: standard error stream for console error output operations.
Example For Streams
1. System.out.println(“hai");
2. System.err.println(“welcome");
int a=System.in.read(); //returns ASCII code of 1st character
System.out.println((char)a); //will print the charact
Java provides two types of streams
• 1.Byte Stream
• 2. Character Stream
Stream with various built-in classes used by the
java IO system
Java Byte Stream
 The java byte stream is defined by two abstract classes
1. InputStream
2. OutputStream.
 The InputStream class used for byte stream based input operations,
 The OutputStream class used for byte stream based output operations.
 The InputStream and OutputStream classes have several classes
to perform various IO operations based on the byte stream.
InputStream class
 The InputStream class has defined as an abstract class
 it has the following methods which have implemented by its concrete classes.
OutputStream class
 The OutputStream class has defined as an abstract class,
 It has the following methods which have implemented by its concrete classes.
i) Reading data using BufferedInputStream
 BufferedInputStream class to read data from the console.
BufferedInputStream(InputStream inputstream)
BufferedInputStream(InputStream inputstream, int bufSize)
 The BufferedInputStream class use a method read( ) to read a
value from the console, or file
Ex 1: Reading from console
EX2: Reading from a file
Writing data using BufferedOutputStream
Character Stream in java
 IO stream manages 16-bit Unicode characters, it is called a character stream.
 The Unicode set is basically a type of character set where each character
corresponds to a specific numeric value within the given character set.
 character stream is defined by two abstract classes, Reader and Writer
 Reader class used for character stream based input operations
 Writer class used for character stream based output operations
 Reader and Writer classes have several concreate classes to perform
various IO operations based on the character stream.
Reader class
 The Reader class has defined as an abstract class
 the following methods implemented by its concrete classes
Writer class
 The Writer class has defined as an abstract class.
 It has the following methods implemented by its concrete classes.
Reading data using BufferedReader
 BufferedReader class to read data from the console.
 The BufferedInputStream class needs InputStreamReaderclass.
 The BufferedReader use a method read( ) to read a value from the console,
or file, or socket.
Example 1 - Reading from console
import java.io.*;
public class ExReading
{
public static void main(String[] args) throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
String name = "";
System.out.print("Please enter your name: ");
name = in.readLine();
System.out.println("Hello, " + name + "!");
Example 2 - Reading from a file
import java.io.*;
class ExReading
{
public static void main(String[] args) throws IOException
{
Reader in = new FileReader(“c/abc.txt”);
try
{
char c = (char)input.read();
System.out.println("Data read from a file - '" + c + "'");
}
catch(Exception e) {
System.out.println(e);
}
finally {
input.close();
Writing data using FileWriter
import java.io.*;
public class ExWriting
{
public static void main(String[] args) throws IOException
{ Writer out = new FileWriter("C:Desktopcse.txt");
msg = "cse";
try
{
out.write(msg);
System.out.println("Writing done!!!");
}
catch(Exception e)
{ System.out.println(e); }
finally
{ out.close(); }
}} }
Writing from a Binary File
 DataOutputStream and DataInputStream enable you to write or read primitive data to or from a
stream.
 They implement the DataOutput and DataInput interfaces,
 DataOutputStream extends FilterOutputStream, which extends OutputStream.
 DataOutputStream defines the following constructor:
DataOutputStream(OutputStream outputStream)
DataOutput defines methods
 final void writeDouble(double value) throws IOException
 final void writeBoolean(boolean value) throws IOException
 final void writeInt(int value) throws IOException
Reading from a Binary File
 DataInputStream is the complement of DataOuputStream. It extends FilterInputStream,which
extends InputStream, and it implements the DataInput interface.
DataInputStream(InputStream inputStream)
Methods:
 double readDouble( ) throws IOException
 boolean readBoolean( ) throws IOException
 int readInt( ) throws IOException
File Class
 File is a built-in class in Java.
 File class has been defined in the java.io package.
 The File class represents a reference to a file or directory.
 File class has various methods to perform operations like creating a file or directory,
reading from a file, updating file content, and deleting a file or directory.
File class constructors
File class Methods
1. boolean canExecute() : Tests whether the application can execute the file denoted by this
abstract pathname.
2. boolean canRead() : Tests whether the application can read the file denoted by this abstract
pathname.
3. boolean canWrite() : Tests whether the application can modify the file denoted by this abstract
pathname.
4. int compareTo(File pathname) : Compares two abstract pathnames lexicographically.
5. boolean createNewFile() : Atomically creates a new, empty file named by this abstract pathname
.
6. static File createTempFile(String prefix, String suffix) : Creates an empty file in the default
temporary-file directory.
8) boolean exists() : Tests whether the file or directory denoted by this abstract pathname exists.
9) String getAbsolutePath() : Returns the absolute pathname string of this abstract pathname.
10) long getFreeSpace() : Returns the number of unallocated bytes in the partition .
11) String getName() : Returns the name of the file or directory denoted by this abstract pathname.
12) String getParent() : Returns the pathname string of this abstract pathname’s parent.
13) File getParentFile() : Returns the abstract pathname of this abstract pathname’s parent.
14) String getPath() : Converts this abstract pathname into a pathname string.
15) boolean isDirectory() : Tests whether the file denoted by this pathname is a directory.
File
import java.io.File;
class FileDemo {
static void p(String s) {
System.out.println(s);
}
public static void main(String args[]) {
File f1 = new File("/java/COPYRIGHT");
p("File Name: " + f1.getName());
p("Path: " + f1.getPath());
p("Abs Path: " + f1.getAbsolutePath());
p("Parent: " + f1.getParent());
p(f1.exists() ? "exists" : "does not exist");
p(f1.canWrite() ? "is writeable" : "is not writeable");
p(f1.canRead() ? "is readable" : "is not readable");
p("is " + (f1.isDirectory() ? "" : "not" + " a directory"));
p(f1.isFile() ? "is normal file" : "might be a named pipe");
p(f1.isAbsolute() ? "is absolute" : "is not absolute");
p("File last modified: " + f1.lastModified());
p("File size: " + f1.length() + " Bytes");
}
}
File
Output
File Name: COPYRIGHT
Path: /java/COPYRIGHT
Abs Path: /java/COPYRIGHT
Parent: /java
exists
is writeable
is readable
is not a directory
is normal file
is absolute
File last modified: 812465204000
File size: 695 Bytes
Creating File using File class
import java.io.*;
class ExFile
{
public static void main(String[] args)
{
try {
File file = new File(“c/abc.txt");
if (file.createNewFile())
{
System.out.println("New File is created!");
} else
{
System.out.println("File already exists.");
}
} catch (IOException e)
{
e.printStackTrace();
}
}
List out all files in a directory or path
import java.io.*;
class ExFileList
{
public static void main(String[] args)
{
File f=new File(“c:/abc/cse");
String filenames[]=f.list();
for(String filename:filenames)
{
System.out.println(filename);
}
}
}

More Related Content

Similar to File Input and output.pptx

Similar to File Input and output.pptx (20)

What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?
 
What is java input and output stream?
What is java input and output stream?What is java input and output stream?
What is java input and output stream?
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Io Streams
Io StreamsIo Streams
Io Streams
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
CORE JAVA-1
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
I/O Streams
I/O StreamsI/O Streams
I/O Streams
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
15. text files
15. text files15. text files
15. text files
 
Java
JavaJava
Java
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
 
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
 
Files streams..
Files streams..Files streams..
Files streams..
 
Stream In Java.pptx
Stream In Java.pptxStream In Java.pptx
Stream In Java.pptx
 
Java 3 Computer Science.pptx
Java 3 Computer Science.pptxJava 3 Computer Science.pptx
Java 3 Computer Science.pptx
 
IO and threads Java
IO and threads JavaIO and threads Java
IO and threads Java
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io Streams
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
 
Basic of Javaio
Basic of JavaioBasic of Javaio
Basic of Javaio
 
Java Tutorial Lab 6
Java Tutorial Lab 6Java Tutorial Lab 6
Java Tutorial Lab 6
 

Recently uploaded

RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998YohFuh
 
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptxthyngster
 
How we prevented account sharing with MFA
How we prevented account sharing with MFAHow we prevented account sharing with MFA
How we prevented account sharing with MFAAndrei Kaleshka
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfLars Albertsson
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...Suhani Kapoor
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPramod Kumar Srivastava
 
04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationshipsccctableauusergroup
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Brighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingBrighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingNeil Barnes
 
RadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdfRadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdfgstagge
 
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样vhwb25kk
 
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...Florian Roscheck
 
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Jack DiGiovanna
 
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一F La
 
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls DubaiDubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls Dubaihf8803863
 
Amazon TQM (2) Amazon TQM (2)Amazon TQM (2).pptx
Amazon TQM (2) Amazon TQM (2)Amazon TQM (2).pptxAmazon TQM (2) Amazon TQM (2)Amazon TQM (2).pptx
Amazon TQM (2) Amazon TQM (2)Amazon TQM (2).pptxAbdelrhman abooda
 
DBA Basics: Getting Started with Performance Tuning.pdf
DBA Basics: Getting Started with Performance Tuning.pdfDBA Basics: Getting Started with Performance Tuning.pdf
DBA Basics: Getting Started with Performance Tuning.pdfJohn Sterrett
 

Recently uploaded (20)

RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998RA-11058_IRR-COMPRESS Do 198 series of 1998
RA-11058_IRR-COMPRESS Do 198 series of 1998
 
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Defence Colony Delhi 💯Call Us 🔝8264348440🔝
 
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptxEMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM  TRACKING WITH GOOGLE ANALYTICS.pptx
EMERCE - 2024 - AMSTERDAM - CROSS-PLATFORM TRACKING WITH GOOGLE ANALYTICS.pptx
 
How we prevented account sharing with MFA
How we prevented account sharing with MFAHow we prevented account sharing with MFA
How we prevented account sharing with MFA
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdf
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
 
04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships
 
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
Deep Generative Learning for All - The Gen AI Hype (Spring 2024)
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
 
Brighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingBrighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data Storytelling
 
RadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdfRadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdf
 
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
 
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
 
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
VIP Call Girls Service Charbagh { Lucknow Call Girls Service 9548273370 } Boo...
 
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
 
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一
办理(Vancouver毕业证书)加拿大温哥华岛大学毕业证成绩单原版一比一
 
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls DubaiDubai Call Girls Wifey O52&786472 Call Girls Dubai
Dubai Call Girls Wifey O52&786472 Call Girls Dubai
 
Amazon TQM (2) Amazon TQM (2)Amazon TQM (2).pptx
Amazon TQM (2) Amazon TQM (2)Amazon TQM (2).pptxAmazon TQM (2) Amazon TQM (2)Amazon TQM (2).pptx
Amazon TQM (2) Amazon TQM (2)Amazon TQM (2).pptx
 
DBA Basics: Getting Started with Performance Tuning.pdf
DBA Basics: Getting Started with Performance Tuning.pdfDBA Basics: Getting Started with Performance Tuning.pdf
DBA Basics: Getting Started with Performance Tuning.pdf
 

File Input and output.pptx

  • 2. File Input and Output Operations:-  File I/O operations are performed using the concept of streams.  A stream means a continuous flow of data.  A stream is a logical container of data that allows us to read from and write to it.  The stream-based IO operations are faster than normal IO operations
  • 4.  Every Java program creates 3 streams automatically.  These streams are attached to the console 1. System.out: standard output stream for console output operations. 2. System.in: standard input stream for console input operations. 3. System.err: standard error stream for console error output operations.
  • 5. Example For Streams 1. System.out.println(“hai"); 2. System.err.println(“welcome"); int a=System.in.read(); //returns ASCII code of 1st character System.out.println((char)a); //will print the charact
  • 6. Java provides two types of streams • 1.Byte Stream • 2. Character Stream
  • 7. Stream with various built-in classes used by the java IO system
  • 8. Java Byte Stream  The java byte stream is defined by two abstract classes 1. InputStream 2. OutputStream.  The InputStream class used for byte stream based input operations,  The OutputStream class used for byte stream based output operations.  The InputStream and OutputStream classes have several classes to perform various IO operations based on the byte stream.
  • 9.
  • 10. InputStream class  The InputStream class has defined as an abstract class  it has the following methods which have implemented by its concrete classes.
  • 11. OutputStream class  The OutputStream class has defined as an abstract class,  It has the following methods which have implemented by its concrete classes.
  • 12. i) Reading data using BufferedInputStream  BufferedInputStream class to read data from the console. BufferedInputStream(InputStream inputstream) BufferedInputStream(InputStream inputstream, int bufSize)  The BufferedInputStream class use a method read( ) to read a value from the console, or file
  • 13. Ex 1: Reading from console
  • 15. Writing data using BufferedOutputStream
  • 16. Character Stream in java  IO stream manages 16-bit Unicode characters, it is called a character stream.  The Unicode set is basically a type of character set where each character corresponds to a specific numeric value within the given character set.  character stream is defined by two abstract classes, Reader and Writer
  • 17.  Reader class used for character stream based input operations  Writer class used for character stream based output operations  Reader and Writer classes have several concreate classes to perform various IO operations based on the character stream.
  • 18.
  • 19. Reader class  The Reader class has defined as an abstract class  the following methods implemented by its concrete classes
  • 20.
  • 21. Writer class  The Writer class has defined as an abstract class.  It has the following methods implemented by its concrete classes.
  • 22.
  • 23. Reading data using BufferedReader  BufferedReader class to read data from the console.  The BufferedInputStream class needs InputStreamReaderclass.  The BufferedReader use a method read( ) to read a value from the console, or file, or socket.
  • 24. Example 1 - Reading from console import java.io.*; public class ExReading { public static void main(String[] args) throws IOException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(isr); String name = ""; System.out.print("Please enter your name: "); name = in.readLine(); System.out.println("Hello, " + name + "!");
  • 25. Example 2 - Reading from a file import java.io.*; class ExReading { public static void main(String[] args) throws IOException { Reader in = new FileReader(“c/abc.txt”); try { char c = (char)input.read(); System.out.println("Data read from a file - '" + c + "'"); } catch(Exception e) { System.out.println(e); } finally { input.close();
  • 26. Writing data using FileWriter import java.io.*; public class ExWriting { public static void main(String[] args) throws IOException { Writer out = new FileWriter("C:Desktopcse.txt"); msg = "cse"; try { out.write(msg); System.out.println("Writing done!!!"); } catch(Exception e) { System.out.println(e); } finally { out.close(); } }} }
  • 27. Writing from a Binary File  DataOutputStream and DataInputStream enable you to write or read primitive data to or from a stream.  They implement the DataOutput and DataInput interfaces,  DataOutputStream extends FilterOutputStream, which extends OutputStream.  DataOutputStream defines the following constructor: DataOutputStream(OutputStream outputStream) DataOutput defines methods  final void writeDouble(double value) throws IOException  final void writeBoolean(boolean value) throws IOException  final void writeInt(int value) throws IOException
  • 28. Reading from a Binary File  DataInputStream is the complement of DataOuputStream. It extends FilterInputStream,which extends InputStream, and it implements the DataInput interface. DataInputStream(InputStream inputStream) Methods:  double readDouble( ) throws IOException  boolean readBoolean( ) throws IOException  int readInt( ) throws IOException
  • 29. File Class  File is a built-in class in Java.  File class has been defined in the java.io package.  The File class represents a reference to a file or directory.  File class has various methods to perform operations like creating a file or directory, reading from a file, updating file content, and deleting a file or directory.
  • 31. File class Methods 1. boolean canExecute() : Tests whether the application can execute the file denoted by this abstract pathname. 2. boolean canRead() : Tests whether the application can read the file denoted by this abstract pathname. 3. boolean canWrite() : Tests whether the application can modify the file denoted by this abstract pathname. 4. int compareTo(File pathname) : Compares two abstract pathnames lexicographically. 5. boolean createNewFile() : Atomically creates a new, empty file named by this abstract pathname . 6. static File createTempFile(String prefix, String suffix) : Creates an empty file in the default temporary-file directory.
  • 32. 8) boolean exists() : Tests whether the file or directory denoted by this abstract pathname exists. 9) String getAbsolutePath() : Returns the absolute pathname string of this abstract pathname. 10) long getFreeSpace() : Returns the number of unallocated bytes in the partition . 11) String getName() : Returns the name of the file or directory denoted by this abstract pathname. 12) String getParent() : Returns the pathname string of this abstract pathname’s parent. 13) File getParentFile() : Returns the abstract pathname of this abstract pathname’s parent. 14) String getPath() : Converts this abstract pathname into a pathname string. 15) boolean isDirectory() : Tests whether the file denoted by this pathname is a directory.
  • 33. File import java.io.File; class FileDemo { static void p(String s) { System.out.println(s); } public static void main(String args[]) { File f1 = new File("/java/COPYRIGHT"); p("File Name: " + f1.getName()); p("Path: " + f1.getPath()); p("Abs Path: " + f1.getAbsolutePath()); p("Parent: " + f1.getParent()); p(f1.exists() ? "exists" : "does not exist"); p(f1.canWrite() ? "is writeable" : "is not writeable"); p(f1.canRead() ? "is readable" : "is not readable"); p("is " + (f1.isDirectory() ? "" : "not" + " a directory")); p(f1.isFile() ? "is normal file" : "might be a named pipe"); p(f1.isAbsolute() ? "is absolute" : "is not absolute"); p("File last modified: " + f1.lastModified()); p("File size: " + f1.length() + " Bytes"); } }
  • 34. File Output File Name: COPYRIGHT Path: /java/COPYRIGHT Abs Path: /java/COPYRIGHT Parent: /java exists is writeable is readable is not a directory is normal file is absolute File last modified: 812465204000 File size: 695 Bytes
  • 35. Creating File using File class import java.io.*; class ExFile { public static void main(String[] args) { try { File file = new File(“c/abc.txt"); if (file.createNewFile()) { System.out.println("New File is created!"); } else { System.out.println("File already exists."); } } catch (IOException e) { e.printStackTrace(); } }
  • 36. List out all files in a directory or path import java.io.*; class ExFileList { public static void main(String[] args) { File f=new File(“c:/abc/cse"); String filenames[]=f.list(); for(String filename:filenames) { System.out.println(filename); } } }