SlideShare una empresa de Scribd logo
1 de 17
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

Más contenido relacionado

La actualidad más candente

Strings in Java
Strings in Java Strings in Java
Strings in Java Hitesh-Java
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java ProgrammingMath-Circle
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonManishJha237
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaEdureka!
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Edureka!
 
Java Basics
Java BasicsJava Basics
Java BasicsSunil OS
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Edureka!
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in javaAdil Mehmoood
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 

La actualidad más candente (20)

Strings in Java
Strings in Java Strings in Java
Strings in Java
 
Arrays in Java
Arrays in Java Arrays in Java
Arrays in Java
 
Java arrays
Java arraysJava arrays
Java arrays
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 
Java constructors
Java constructorsJava constructors
Java constructors
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Java ArrayList Tutorial | Edureka
Java ArrayList Tutorial | EdurekaJava ArrayList Tutorial | Edureka
Java ArrayList Tutorial | Edureka
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
 
String in java
String in javaString in java
String in java
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 

Destacado

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 javaJyoti Verma
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread managementxuehan zhu
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And MultithreadingShraddha
 
14 file handling
14 file handling14 file handling
14 file handlingAPU
 
Java string handling
Java string handlingJava string handling
Java string handlingSalman Khan
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling pptJavabynataraJ
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 

Destacado (11)

14 hql
14 hql14 hql
14 hql
 
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
 
14 file handling
14 file handling14 file handling
14 file handling
 
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 a 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 javaKavitha713564
 
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 javaJayasankarPR2
 
File Input & Output
File Input & OutputFile Input & Output
File Input & OutputPRN USM
 
File Handling in Java Oop presentation
File Handling in Java Oop presentationFile Handling in Java Oop presentation
File Handling in Java Oop presentationAzeemaj101
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and OutputEduardo Bergavera
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12Vince Vo
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdfSudhanshiBakre1
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugevsol7206
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and outputRiccardo 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
 

Similar a 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
 
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
 
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
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
 
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
 

Último

Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationShrmpro
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsBert Jan Schrijver
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburgmasabamasaba
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 

Último (20)

Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 

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