SlideShare a Scribd company logo
3
Most read
4
Most read
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

PPTX
Introduction to AngularJS
PPT
PPTX
Form using html and java script validation
PDF
Constants, Variables and Data Types in Java
PPTX
Typescript ppt
PPTX
Array in c#
PPT
javascript-basics.ppt
Introduction to AngularJS
Form using html and java script validation
Constants, Variables and Data Types in Java
Typescript ppt
Array in c#
javascript-basics.ppt

What's hot (20)

PPT
Looping statements in Java
PPT
Input and output in C++
PPT
Javascript
PDF
Javascript basics
PPTX
Core java complete ppt(note)
PDF
Introduction to django framework
PPSX
Javascript variables and datatypes
PDF
Introduction to Bootstrap
PPT
Introduction to JavaScript
PPT
javaScript.ppt
PDF
Android Location and Maps
PPTX
Inner classes in java
PPTX
Switch statement, break statement, go to statement
PPTX
Introduction to JAVA
ODP
Object Oriented Javascript
PDF
Basics of JavaScript
PPTX
PPTX
07 java variables
DOCX
Structure in c sharp
Looping statements in Java
Input and output in C++
Javascript
Javascript basics
Core java complete ppt(note)
Introduction to django framework
Javascript variables and datatypes
Introduction to Bootstrap
Introduction to JavaScript
javaScript.ppt
Android Location and Maps
Inner classes in java
Switch statement, break statement, go to statement
Introduction to JAVA
Object Oriented Javascript
Basics of JavaScript
07 java variables
Structure in c sharp
Ad

Viewers also liked (13)

PPT
PPT
Java Input Output and File Handling
PPT
7 streams and error handling in java
PDF
Java Programming - 06 java file io
PDF
[Java concurrency]01.thread management
PPT
Java And Multithreading
PPT
14 file handling
 
PPTX
Java string handling
PDF
Java Course 8: I/O, Files and Streams
PDF
PDF
Java exception handling ppt
PPS
Java Exception handling
PPT
Java multi threading
Java Input Output and File Handling
7 streams and error handling in java
Java Programming - 06 java file io
[Java concurrency]01.thread management
Java And Multithreading
14 file handling
 
Java string handling
Java Course 8: I/O, Files and Streams
Java exception handling ppt
Java Exception handling
Java multi threading
Ad

Similar to Java file (20)

PDF
Java I/o streams
PPS
Files & IO in Java
PDF
Input File dalam C++
PPTX
15. text files
PPTX
chapter 2(IO and stream)/chapter 2, IO and stream
PPTX
Input output files in java
PDF
Basic i/o & file handling in java
PPT
File Input & Output
PPT
Comp102 lec 11
PPTX
Python files creation read,write Unit 5.pptx
PPTX
File Handling in Java Oop presentation
PPT
Javaio
PPT
Javaio
PDF
Java IO Stream, the introduction to Streams
PPT
Java căn bản - Chapter12
PPT
Chapter 12 - File Input and Output
PDF
File Handling in Java.pdf
PDF
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
PDF
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
PPTX
Java - Processing input and output
Java I/o streams
Files & IO in Java
Input File dalam C++
15. text files
chapter 2(IO and stream)/chapter 2, IO and stream
Input output files in java
Basic i/o & file handling in java
File Input & Output
Comp102 lec 11
Python files creation read,write Unit 5.pptx
File Handling in Java Oop presentation
Javaio
Javaio
Java IO Stream, the introduction to Streams
Java căn bản - Chapter12
Chapter 12 - File Input and Output
File Handling in Java.pdf
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
Java - Processing input and output

Recently uploaded (20)

PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Digital Strategies for Manufacturing Companies
PPT
Introduction Database Management System for Course Database
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
AI in Product Development-omnex systems
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
history of c programming in notes for students .pptx
PPTX
Transform Your Business with a Software ERP System
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
top salesforce developer skills in 2025.pdf
PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PPTX
ai tools demonstartion for schools and inter college
ISO 45001 Occupational Health and Safety Management System
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Digital Strategies for Manufacturing Companies
Introduction Database Management System for Course Database
How to Choose the Right IT Partner for Your Business in Malaysia
2025 Textile ERP Trends: SAP, Odoo & Oracle
Operating system designcfffgfgggggggvggggggggg
AI in Product Development-omnex systems
Odoo Companies in India – Driving Business Transformation.pdf
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
How to Migrate SBCGlobal Email to Yahoo Easily
Softaken Excel to vCard Converter Software.pdf
history of c programming in notes for students .pptx
Transform Your Business with a Software ERP System
How Creative Agencies Leverage Project Management Software.pdf
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Which alternative to Crystal Reports is best for small or large businesses.pdf
top salesforce developer skills in 2025.pdf
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
ai tools demonstartion for schools and inter college

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