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 (20)

PDF
Arrays in Java
Naz Abdalla
 
PDF
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Edureka!
 
PPTX
Packages
Monika Mishra
 
PPTX
Css types internal, external and inline (1)
Webtech Learning
 
PPTX
Applet and graphics programming
srijavel
 
PPTX
JavaScript Basics
Bhanuka Uyanage
 
PPT
Scripting languages
teach4uin
 
PPT
sets and maps
Rajkattamuri
 
PPTX
Type casting in java
Farooq Baloch
 
DOCX
JDK,JRE,JVM
Cognizant
 
PPT
Awt controls ppt
soumyaharitha
 
PDF
java.io - streams and files
Marcello Thiry
 
PPT
Synchronization.37
myrajendra
 
PPTX
Java Server Pages(jsp)
Manisha Keim
 
PPTX
Java script
Abhishek Kesharwani
 
PPTX
Core java complete ppt(note)
arvind pandey
 
PPTX
Java Program Structure
Manish Tiwari
 
PPT
Packages in java
jamunaashok
 
PPTX
File and directory
Sunil Kafle
 
PPT
11 deployment diagrams
Baskarkncet
 
Arrays in Java
Naz Abdalla
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Edureka!
 
Packages
Monika Mishra
 
Css types internal, external and inline (1)
Webtech Learning
 
Applet and graphics programming
srijavel
 
JavaScript Basics
Bhanuka Uyanage
 
Scripting languages
teach4uin
 
sets and maps
Rajkattamuri
 
Type casting in java
Farooq Baloch
 
JDK,JRE,JVM
Cognizant
 
Awt controls ppt
soumyaharitha
 
java.io - streams and files
Marcello Thiry
 
Synchronization.37
myrajendra
 
Java Server Pages(jsp)
Manisha Keim
 
Java script
Abhishek Kesharwani
 
Core java complete ppt(note)
arvind pandey
 
Java Program Structure
Manish Tiwari
 
Packages in java
jamunaashok
 
File and directory
Sunil Kafle
 
11 deployment diagrams
Baskarkncet
 

Viewers also liked (13)

PPT
14 hql
thirumuru2012
 
PPT
Java Input Output and File Handling
Sunil OS
 
PPT
7 streams and error handling in java
Jyoti Verma
 
PDF
Java Programming - 06 java file io
Danairat Thanabodithammachari
 
PDF
[Java concurrency]01.thread management
xuehan zhu
 
PPT
Java And Multithreading
Shraddha
 
PPT
14 file handling
APU
 
PPTX
Java string handling
Salman Khan
 
PDF
Java Course 8: I/O, Files and Streams
Anton Keks
 
PDF
Java I/O
Jussi Pohjolainen
 
PDF
Java exception handling ppt
JavabynataraJ
 
PPS
Java Exception handling
kamal kotecha
 
PPT
Java multi threading
Raja Sekhar
 
Java Input Output and File Handling
Sunil OS
 
7 streams and error handling in java
Jyoti Verma
 
Java Programming - 06 java file io
Danairat Thanabodithammachari
 
[Java concurrency]01.thread management
xuehan zhu
 
Java And Multithreading
Shraddha
 
14 file handling
APU
 
Java string handling
Salman Khan
 
Java Course 8: I/O, Files and Streams
Anton Keks
 
Java exception handling ppt
JavabynataraJ
 
Java Exception handling
kamal kotecha
 
Java multi threading
Raja Sekhar
 
Ad

Similar to Java file (20)

PPT
ch09.ppt
NiharikaDubey17
 
PPT
Comp102 lec 11
Fraz Bakhsh
 
PPSX
JDBC
Hitesh-Java
 
PPS
Files & IO in Java
CIB Egypt
 
PDF
Basic java tutorial
Pedro De Almeida
 
DOCX
PAGE 1Input output for a file tutorialStreams and File IOI.docx
alfred4lewis58146
 
PDF
OOPs with Java_unit2.pdf. sarthak bookkk
Sarthak964187
 
PPTX
File Handling in Java Oop presentation
Azeemaj101
 
PDF
Java IO Stream, the introduction to Streams
ranganadh6
 
PDF
Absolute Java 5th Edition Walter Savitch Solutions Manual
labakybrasca33
 
DOCX
FileHandling.docx
NavneetSheoran3
 
PPTX
Session 23 - JDBC
PawanMM
 
PPT
File Input and Output in Java Programing language
BurhanKhan774154
 
PPTX
Java Tutorial Lab 6
Berk Soysal
 
PDF
File Handling in Java.pdf
SudhanshiBakre1
 
PPTX
File Input and output.pptx
cherryreddygannu
 
PPT
Java File I/O
Canterbury HS
 
PPTX
Random Class & File Handling.pptx
VijalJain3
 
PDF
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
PPTX
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 
ch09.ppt
NiharikaDubey17
 
Comp102 lec 11
Fraz Bakhsh
 
Files & IO in Java
CIB Egypt
 
Basic java tutorial
Pedro De Almeida
 
PAGE 1Input output for a file tutorialStreams and File IOI.docx
alfred4lewis58146
 
OOPs with Java_unit2.pdf. sarthak bookkk
Sarthak964187
 
File Handling in Java Oop presentation
Azeemaj101
 
Java IO Stream, the introduction to Streams
ranganadh6
 
Absolute Java 5th Edition Walter Savitch Solutions Manual
labakybrasca33
 
FileHandling.docx
NavneetSheoran3
 
Session 23 - JDBC
PawanMM
 
File Input and Output in Java Programing language
BurhanKhan774154
 
Java Tutorial Lab 6
Berk Soysal
 
File Handling in Java.pdf
SudhanshiBakre1
 
File Input and output.pptx
cherryreddygannu
 
Java File I/O
Canterbury HS
 
Random Class & File Handling.pptx
VijalJain3
 
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 
Ad

Recently uploaded (20)

PPTX
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 

Java file

  • 1. Java File Reading and Writing Files in Java Kazi Sanghati Sowharda Haque, Email: [email protected]
  • 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: [email protected]