SlideShare a Scribd company logo
Java File
Reading and Writing Files in Java
Kazi Sanghati Sowharda Haque, Email: sonnetdp@gmail.com
About File Handling in Java
lA simple guide to reading and writing files in the Java
programming language.
lThe key things to remember are as follows.
Reading File in Java
lRead files using these classes:
lFileReader for text files in your system's default
encoding (for example, files containing Western
European characters on a Western European
computer).
lFileInputStream for binary files and text files
that contain 'weird' characters.
Reading Ordinary Text Files in Java
lIf you want to read an ordinary text file in your system's default
encoding (usually the case most of the time for most people), use
FileReader and wrap it in a BufferedReader.
lIn the following program, we read a file called "temp.txt" and
output the file line by line on the console.
Code to Read ordinary text file
import java.io.*;
public class Test {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "temp.txt";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
// Always close files.
Code to Read ordinary text file
(continued)
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
Reading Binary Files in Java
lIf you want to read a binary file, or a text file containing 'weird'
characters (ones that your system doesn't deal with by default), you
need to use FileInputStream instead of FileReader. Instead of
wrapping FileInputStream in a buffer, FileInputStream defines a
method called read() that lets you fill a buffer with data,
automatically reading just enough bytes to fill the buffer (or less if
there aren't that many bytes left to read).
Code to Read a binary File in Java
import java.io.*;
public class Test {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "temp.txt";
try {
// Use this for reading the data.
byte[] buffer = new byte[1000];
FileInputStream inputStream =
new FileInputStream(fileName);
// read fills buffer with data and returns
// the number of bytes read (which of course
// may be less than the buffer size, but
// it will never be more).
int total = 0;
int nRead = 0;
while((nRead = inputStream.read(buffer)) != -1) {
// Convert to String so we can display it.
// Of course you wouldn't want to do this with
// a 'real' binary file.
System.out.println(new String(buffer));
Code to Read a binary File in Java
(continued)
// Always close files.
inputStream.close();
System.out.println("Read " + total + " bytes");
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
Writing Files in Java
lTo write a text file in Java, use FileWriter
instead of FileReader, and
lBufferedOutputWriter instead of
BufferedOutputReader
Writing Text Files in Java
lHere's an example program that
creates a file called 'temp.txt'
and writes some lines of text to
it.
Code to Write Text Files in Java
import java.io.*;
public class Test {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "temp.txt";
try {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(fileName);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
// Note that write() does not automatically
// append a newline character.
bufferedWriter.write("Hello there,");
bufferedWriter.write(" here is some text.");
bufferedWriter.newLine();
bufferedWriter.write("We are writing");
bufferedWriter.write(" the text to the file.");
Code to Write Text Files in Java
(continued)
// Always close files.
bufferedWriter.close();
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
Writing Binary Files in Java
lYou can create and write to a binary file in Java using much the
same techniques that we used to read binary files, except that we
need FileOutputStream instead of FileInputStream.
lIn the following example we write out some text as binary data to
the file. Usually of course, you'd probably want to write some
proprietary file format or something.
Code to Write Binary Files in Java
import java.io.*;
public class Test {
public static void main(String [] args) {
// The name of the file to create.
String fileName = "temp.txt";
try {
// Put some bytes in a buffer so we can
// write them. Usually this would be
// image data or something. Or it might
// be unicode text.
String bytes = "Hello theren";
byte[] buffer = bytes.getBytes();
FileOutputStream outputStream =
new FileOutputStream(fileName);
// write() writes as many bytes from the buffer
// as the length of the buffer. You can also
// use
// write(buffer, offset, length)
// if you want to write a specific number of
// bytes, or only part of the buffer.
outputStream.write(buffer);
Code to Write Binary Files in Java
(continued)
// Always close files.
outputStream.close();
System.out.println("Wrote " + buffer.length +
" bytes");
}
catch(IOException ex) {
System.out.println(
"Error writing file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
Question?
lPlease fill free to ask any
question.
lEmail: sonnetdp@gmail.com

More Related Content

What's hot

Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
PhD Research Scholar
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
jaimefrozr
 
Function in C
Function in CFunction in C
Function in C
Dr. Abhineet Anand
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
Arzath Areeff
 
Files and streams
Files and streamsFiles and streams
Files and streams
Pranali Chaudhari
 
class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
Chapter 13 - Recursion
Chapter 13 - RecursionChapter 13 - Recursion
Chapter 13 - RecursionAdan Hubahib
 
Exception handling
Exception handlingException handling
Exception handling
Ardhendu Nandi
 
Java constructors
Java constructorsJava constructors
Java constructors
QUONTRASOLUTIONS
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
Elizabeth Thomas
 
14 file handling
14 file handling14 file handling
14 file handlingAPU
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
SIVASHANKARIRAJAN
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java ppt
kunal kishore
 
Structure of java program diff c- cpp and java
Structure of java program  diff c- cpp and javaStructure of java program  diff c- cpp and java
Structure of java program diff c- cpp and java
Madishetty Prathibha
 
Java Programming
Java ProgrammingJava Programming
Java Programming
Anjan Mahanta
 
C# in depth
C# in depthC# in depth
C# in depth
Arnon Axelrod
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
JayasankarPR2
 
Java Streams
Java StreamsJava Streams
Java Streams
M Vishnuvardhan Reddy
 

What's hot (20)

Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
Function in C
Function in CFunction in C
Function in C
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
class and objects
class and objectsclass and objects
class and objects
 
Chapter 13 - Recursion
Chapter 13 - RecursionChapter 13 - Recursion
Chapter 13 - Recursion
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Exception handling
Exception handlingException handling
Exception handling
 
Java constructors
Java constructorsJava constructors
Java constructors
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
 
14 file handling
14 file handling14 file handling
14 file handling
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java ppt
 
Structure of java program diff c- cpp and java
Structure of java program  diff c- cpp and javaStructure of java program  diff c- cpp and java
Structure of java program diff c- cpp and java
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
C# in depth
C# in depthC# in depth
C# in depth
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
 
Java Streams
Java StreamsJava Streams
Java Streams
 

Viewers also liked

Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
Sunil OS
 
7 streams and error handling in java
7 streams and error handling in java7 streams and error handling in java
7 streams and error handling in java
Jyoti Verma
 
Java Programming - 06 java file io
Java Programming - 06 java file ioJava Programming - 06 java file io
Java Programming - 06 java file io
Danairat Thanabodithammachari
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread management
xuehan zhu
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Java string handling
Java string handlingJava string handling
Java string handling
Salman Khan
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
JavabynataraJ
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 

Viewers also liked (11)

14 hql
14 hql14 hql
14 hql
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
7 streams and error handling in java
7 streams and error handling in java7 streams and error handling in java
7 streams and error handling in java
 
Java Programming - 06 java file io
Java Programming - 06 java file ioJava Programming - 06 java file io
Java Programming - 06 java file io
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread management
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Java I/O
Java I/OJava I/O
Java I/O
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 

Similar to Java file

Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in JavaCIB Egypt
 
Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++Teguh Nugraha
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
PRN USM
 
File Handling in Java Oop presentation
File Handling in Java Oop presentationFile Handling in Java Oop presentation
File Handling in Java Oop presentation
Azeemaj101
 
Javaio
JavaioJavaio
Javaio
Jaya Jeswani
 
Javaio
JavaioJavaio
Javaio
Jaya Jeswani
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12Vince Vo
 
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
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
SudhanshiBakre1
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and output
Riccardo Cardin
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handlingpinkpreet_kaur
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3sotlsoc
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
22261A1201ABDULMUQTA
 

Similar to Java file (20)

Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in Java
 
Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++
 
15. text files
15. text files15. text files
15. text files
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 
Comp102 lec 11
Comp102   lec 11Comp102   lec 11
Comp102 lec 11
 
File Handling in Java Oop presentation
File Handling in Java Oop presentationFile Handling in Java Oop presentation
File Handling in Java Oop presentation
 
Javaio
JavaioJavaio
Javaio
 
Javaio
JavaioJavaio
Javaio
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and output
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
 

Recently uploaded

Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 

Recently uploaded (20)

Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 

Java file

  • 1. Java File Reading and Writing Files in Java Kazi Sanghati Sowharda Haque, Email: sonnetdp@gmail.com
  • 2. About File Handling in Java lA simple guide to reading and writing files in the Java programming language. lThe key things to remember are as follows.
  • 3. Reading File in Java lRead files using these classes: lFileReader for text files in your system's default encoding (for example, files containing Western European characters on a Western European computer). lFileInputStream for binary files and text files that contain 'weird' characters.
  • 4. Reading Ordinary Text Files in Java lIf you want to read an ordinary text file in your system's default encoding (usually the case most of the time for most people), use FileReader and wrap it in a BufferedReader. lIn the following program, we read a file called "temp.txt" and output the file line by line on the console.
  • 5. Code to Read ordinary text file import java.io.*; public class Test { public static void main(String [] args) { // The name of the file to open. String fileName = "temp.txt"; // This will reference one line at a time String line = null; try { // FileReader reads text files in the default encoding. FileReader fileReader = new FileReader(fileName); // Always wrap FileReader in BufferedReader. BufferedReader bufferedReader = new BufferedReader(fileReader); while((line = bufferedReader.readLine()) != null) { System.out.println(line); } // Always close files.
  • 6. Code to Read ordinary text file (continued) catch(FileNotFoundException ex) { System.out.println( "Unable to open file '" + fileName + "'"); } catch(IOException ex) { System.out.println( "Error reading file '" + fileName + "'"); // Or we could just do this: // ex.printStackTrace(); } } }
  • 7. Reading Binary Files in Java lIf you want to read a binary file, or a text file containing 'weird' characters (ones that your system doesn't deal with by default), you need to use FileInputStream instead of FileReader. Instead of wrapping FileInputStream in a buffer, FileInputStream defines a method called read() that lets you fill a buffer with data, automatically reading just enough bytes to fill the buffer (or less if there aren't that many bytes left to read).
  • 8. Code to Read a binary File in Java import java.io.*; public class Test { public static void main(String [] args) { // The name of the file to open. String fileName = "temp.txt"; try { // Use this for reading the data. byte[] buffer = new byte[1000]; FileInputStream inputStream = new FileInputStream(fileName); // read fills buffer with data and returns // the number of bytes read (which of course // may be less than the buffer size, but // it will never be more). int total = 0; int nRead = 0; while((nRead = inputStream.read(buffer)) != -1) { // Convert to String so we can display it. // Of course you wouldn't want to do this with // a 'real' binary file. System.out.println(new String(buffer));
  • 9. Code to Read a binary File in Java (continued) // Always close files. inputStream.close(); System.out.println("Read " + total + " bytes"); } catch(FileNotFoundException ex) { System.out.println( "Unable to open file '" + fileName + "'"); } catch(IOException ex) { System.out.println( "Error reading file '" + fileName + "'"); // Or we could just do this: // ex.printStackTrace(); } } }
  • 10. Writing Files in Java lTo write a text file in Java, use FileWriter instead of FileReader, and lBufferedOutputWriter instead of BufferedOutputReader
  • 11. Writing Text Files in Java lHere's an example program that creates a file called 'temp.txt' and writes some lines of text to it.
  • 12. Code to Write Text Files in Java import java.io.*; public class Test { public static void main(String [] args) { // The name of the file to open. String fileName = "temp.txt"; try { // Assume default encoding. FileWriter fileWriter = new FileWriter(fileName); // Always wrap FileWriter in BufferedWriter. BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); // Note that write() does not automatically // append a newline character. bufferedWriter.write("Hello there,"); bufferedWriter.write(" here is some text."); bufferedWriter.newLine(); bufferedWriter.write("We are writing"); bufferedWriter.write(" the text to the file.");
  • 13. Code to Write Text Files in Java (continued) // Always close files. bufferedWriter.close(); } catch(IOException ex) { System.out.println( "Error writing to file '" + fileName + "'"); // Or we could just do this: // ex.printStackTrace(); } } }
  • 14. Writing Binary Files in Java lYou can create and write to a binary file in Java using much the same techniques that we used to read binary files, except that we need FileOutputStream instead of FileInputStream. lIn the following example we write out some text as binary data to the file. Usually of course, you'd probably want to write some proprietary file format or something.
  • 15. Code to Write Binary Files in Java import java.io.*; public class Test { public static void main(String [] args) { // The name of the file to create. String fileName = "temp.txt"; try { // Put some bytes in a buffer so we can // write them. Usually this would be // image data or something. Or it might // be unicode text. String bytes = "Hello theren"; byte[] buffer = bytes.getBytes(); FileOutputStream outputStream = new FileOutputStream(fileName); // write() writes as many bytes from the buffer // as the length of the buffer. You can also // use // write(buffer, offset, length) // if you want to write a specific number of // bytes, or only part of the buffer. outputStream.write(buffer);
  • 16. Code to Write Binary Files in Java (continued) // Always close files. outputStream.close(); System.out.println("Wrote " + buffer.length + " bytes"); } catch(IOException ex) { System.out.println( "Error writing file '" + fileName + "'"); // Or we could just do this: // ex.printStackTrace(); } } }
  • 17. Question? lPlease fill free to ask any question. lEmail: sonnetdp@gmail.com