SlideShare une entreprise Scribd logo
1  sur  17
Files & IO Mohamed Shahpoup
Files and Streams:  definition •  Files—these exist on a local file system •  Streams—these represent a “stream” of characters coming from some location. •  Before you can read from a file, you must  open  it.  •  After you are done reading from a file, you must  close  it.
Files and Streams •  There are two common varieties of  reading : —  reading  characters  ( a character is 16 bits long). —  reading  bytes  ( a byte is 8 bits long). •  There are two common varieties of  writing : —  writing  characters  ( a character is 16 bits long). —  writing  bytes  ( a byte is 8 bits long).
Reading Characters •  When we say we want to read characters, it means we never want to move things like images. •  Each of the bubbles in the list below represents a Java class that is designed to read a certain type of character. Each of these is designed for a particular case. Reader  is an abstract class
Writing Characters •  When we are writing characters, the same idea applies. •  Each of the bubbles in the list below represents a Java class that is designed to write a certain type of character. Each of these is designed for a particular case. Writer  is an abstract class
Reading Bytes •  Below is the list of classes you use when you want to read at a finer grain than just characters. That would be  bytes. InputStream   is an abstract class
Writing Bytes •  Below is the list of classes you use when you want to write  bytes . OutputStream  is an abstract class
Reading Characters from a File •  Say you want to read from a file: •  You will need to  open  the file. •  You will need to read from the file to the  end . •  You will need to  close  the file.
•  First of all, what is a   file ? •  A file is an instance of the class   File import java.io; public class FileRead { public FileRead() { File inFile = new File( “Gavin King.txt” ); } public static void main( String[] args ) { FileRead fr = new FileRead(); } } Reading Characters from a File All the classes used in I/O come from this package.
import java.io; public class FileRead { public FileRead() { try {   File inFile = new File( “Gavin King.txt” ); } catch( IOException io ) {   System.out.println( “IOException, io=“ + io ); } } public static void main( String[] args ) { FileRead fr = new FileRead(); } Because the constructor on  File  throws an IOException, we are forced to place it in a try-catch block Reading Characters from a File
public class FileRead { public FileRead() { try {   File  inFile   = new File( “infile.txt” );   File  outFile  = new File( “outFile.txt” );   FileReader  fr  = new FileReader(  inFile  );   FileWriter  fw  = new FileWriter(  outFile  );   int c = 0; boolean keepReading = true;   while( keepReading )   { c =  fr .read(); if( c == -1 )’ {   keepReading = false; } else {    fw .write( c ); }   }   fr.close();   fw.close(); } What is this? We read a character but store it as an integer? That’s right. Although we  read  an  int , the  FileWriter  understands that it needs to  write  these as characters.
Reading Bytes from a File •  The approach for reading  bytes  is nearly the same. •  The difference comes in the classes we choose to do the  reading and writing.
public class FileRead { public FileRead() { try {   File inFile  = new File( “inFile.txt” );   File outFile = new File( “outFile.txt” );   FileInputStream  fis = new  FileInputStream ( inFile );   FileOutputStream  fos = new  FileOutputStream ( outFile );   int c = 0; boolean keepReading = true;   while( keepReading )   { c = fis.read(); if( c == -1 )’ {   keepReading = false; } else {    fos.write( c ); }   }   fr.close();   fw.close(); }
Alternatives for Efficiency •  As you can imagine, reading a byte or a character at a time is pretty inefficient. •  For that reason, there are alternatives.  •  The best one is the  BufferedReader . This class gathers a chunk of data at a read.
public class FileRead { public FileRead() { try {   File inFile  = new File( “C:/orig/aFile.txt” );   File outFile = new File( “C:/final/outFile.txt” );   FileReader  fr  = new FileReader( inFile );   BufferedReader   br  = new  BufferedReader (  fr  );   FileWriter  fw  = new FileWriter( outFile );   BufferedWriter   bw  = new  BufferedWriter (  fw  );   String  temp  = null; boolean keepReading = true;   while( keepReading )   { temp  =  br . readLine(); if(  temp  == null)  {   keepReading = false; } else {    bw .write(  temp  ); }   }   br .close();   fr .close();   bw .close();   fw .close(); } Now, we have added a  BufferedReader , which allows us to read a line at a time. The BufferedWriter also allows us to write an entire  String
 
 

Contenu connexe

Tendances

Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)Om Ganesh
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output ConceptsVicter Paul
 
IO In Java
IO In JavaIO In Java
IO In Javaparag
 
14 file handling
14 file handling14 file handling
14 file handlingAPU
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streamsbabak danyal
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and filesMarcello Thiry
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and OutputEduardo Bergavera
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Filesprimeteacher32
 
File Input & Output
File Input & OutputFile Input & Output
File Input & OutputPRN USM
 
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
 
Byte stream classes.49
Byte stream classes.49Byte stream classes.49
Byte stream classes.49myrajendra
 
File Handling in Java Oop presentation
File Handling in Java Oop presentationFile Handling in Java Oop presentation
File Handling in Java Oop presentationAzeemaj101
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47myrajendra
 

Tendances (20)

Java stream
Java streamJava stream
Java stream
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
Java I/O
Java I/OJava I/O
Java I/O
 
Input output streams
Input output streamsInput output streams
Input output streams
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
IO In Java
IO In JavaIO In Java
IO In Java
 
Files in java
Files in javaFiles in java
Files in java
 
14 file handling
14 file handling14 file handling
14 file handling
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streams
 
Java Streams
Java StreamsJava Streams
Java Streams
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
32.java input-output
32.java input-output32.java input-output
32.java input-output
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 
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
 
Javaiostream
JavaiostreamJavaiostream
Javaiostream
 
Byte stream classes.49
Byte stream classes.49Byte stream classes.49
Byte stream classes.49
 
File Handling in Java Oop presentation
File Handling in Java Oop presentationFile Handling in Java Oop presentation
File Handling in Java Oop presentation
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47
 

En vedette

Design Pattern From Java To Ruby
Design Pattern From Java To RubyDesign Pattern From Java To Ruby
Design Pattern From Java To Rubyyelogic
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead ProgrammingNishant Mevawala
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVAVikram Kalyani
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Javakoji lin
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Javaparag
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in JavaM. Raihan
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaRaghu nath
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
Java: Java Applets
Java: Java AppletsJava: Java Applets
Java: Java AppletsTareq Hasan
 

En vedette (18)

My History
My HistoryMy History
My History
 
Design Pattern From Java To Ruby
Design Pattern From Java To RubyDesign Pattern From Java To Ruby
Design Pattern From Java To Ruby
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead Programming
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
 
Threads in java
Threads in javaThreads in java
Threads in java
 
Java applets
Java appletsJava applets
Java applets
 
Applet java
Applet javaApplet java
Applet java
 
27 applet programming
27  applet programming27  applet programming
27 applet programming
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Java applets
Java appletsJava applets
Java applets
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java: Java Applets
Java: Java AppletsJava: Java Applets
Java: Java Applets
 

Similaire à Files & IO in Java (20)

File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
 
Chap 9 : I/O and Streams (scjp/ocjp)
Chap 9 : I/O and Streams (scjp/ocjp)Chap 9 : I/O and Streams (scjp/ocjp)
Chap 9 : I/O and Streams (scjp/ocjp)
 
03-01-File Handling.pdf
03-01-File Handling.pdf03-01-File Handling.pdf
03-01-File Handling.pdf
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
 
05io
05io05io
05io
 
03-01-File Handling python.pptx
03-01-File Handling python.pptx03-01-File Handling python.pptx
03-01-File Handling python.pptx
 
pspp-rsk.pptx
pspp-rsk.pptxpspp-rsk.pptx
pspp-rsk.pptx
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
JAVA
JAVAJAVA
JAVA
 
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
 
Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++
 
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is hereCHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
 
Python-files
Python-filesPython-files
Python-files
 

Dernier

Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...Mark Carrigan
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project researchCaitlinCummins3
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文中 央社
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptxPoojaSen20
 
Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).Mohamed Rizk Khodair
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽中 央社
 
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45MysoreMuleSoftMeetup
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxneillewis46
 
Championnat de France de Tennis de table/
Championnat de France de Tennis de table/Championnat de France de Tennis de table/
Championnat de France de Tennis de table/siemaillard
 
demyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxdemyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxMohamed Rizk Khodair
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024Borja Sotomayor
 
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...Denish Jangid
 
How to Manage Closest Location in Odoo 17 Inventory
How to Manage Closest Location in Odoo 17 InventoryHow to Manage Closest Location in Odoo 17 Inventory
How to Manage Closest Location in Odoo 17 InventoryCeline George
 
MichaelStarkes_UncutGemsProjectSummary.pdf
MichaelStarkes_UncutGemsProjectSummary.pdfMichaelStarkes_UncutGemsProjectSummary.pdf
MichaelStarkes_UncutGemsProjectSummary.pdfmstarkes24
 
Financial Accounting IFRS, 3rd Edition-dikompresi.pdf
Financial Accounting IFRS, 3rd Edition-dikompresi.pdfFinancial Accounting IFRS, 3rd Edition-dikompresi.pdf
Financial Accounting IFRS, 3rd Edition-dikompresi.pdfMinawBelay
 
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...Nguyen Thanh Tu Collection
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppCeline George
 

Dernier (20)

Word Stress rules esl .pptx
Word Stress rules esl               .pptxWord Stress rules esl               .pptx
Word Stress rules esl .pptx
 
Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
IPL Online Quiz by Pragya; Question Set.
IPL Online Quiz by Pragya; Question Set.IPL Online Quiz by Pragya; Question Set.
IPL Online Quiz by Pragya; Question Set.
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptx
 
Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
 
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
 
“O BEIJO” EM ARTE .
“O BEIJO” EM ARTE                       .“O BEIJO” EM ARTE                       .
“O BEIJO” EM ARTE .
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptx
 
Championnat de France de Tennis de table/
Championnat de France de Tennis de table/Championnat de France de Tennis de table/
Championnat de France de Tennis de table/
 
demyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxdemyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptx
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
 
How to Manage Closest Location in Odoo 17 Inventory
How to Manage Closest Location in Odoo 17 InventoryHow to Manage Closest Location in Odoo 17 Inventory
How to Manage Closest Location in Odoo 17 Inventory
 
MichaelStarkes_UncutGemsProjectSummary.pdf
MichaelStarkes_UncutGemsProjectSummary.pdfMichaelStarkes_UncutGemsProjectSummary.pdf
MichaelStarkes_UncutGemsProjectSummary.pdf
 
Financial Accounting IFRS, 3rd Edition-dikompresi.pdf
Financial Accounting IFRS, 3rd Edition-dikompresi.pdfFinancial Accounting IFRS, 3rd Edition-dikompresi.pdf
Financial Accounting IFRS, 3rd Edition-dikompresi.pdf
 
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge App
 

Files & IO in Java

  • 1. Files & IO Mohamed Shahpoup
  • 2. Files and Streams: definition • Files—these exist on a local file system • Streams—these represent a “stream” of characters coming from some location. • Before you can read from a file, you must open it. • After you are done reading from a file, you must close it.
  • 3. Files and Streams • There are two common varieties of reading : — reading characters ( a character is 16 bits long). — reading bytes ( a byte is 8 bits long). • There are two common varieties of writing : — writing characters ( a character is 16 bits long). — writing bytes ( a byte is 8 bits long).
  • 4. Reading Characters • When we say we want to read characters, it means we never want to move things like images. • Each of the bubbles in the list below represents a Java class that is designed to read a certain type of character. Each of these is designed for a particular case. Reader is an abstract class
  • 5. Writing Characters • When we are writing characters, the same idea applies. • Each of the bubbles in the list below represents a Java class that is designed to write a certain type of character. Each of these is designed for a particular case. Writer is an abstract class
  • 6. Reading Bytes • Below is the list of classes you use when you want to read at a finer grain than just characters. That would be bytes. InputStream is an abstract class
  • 7. Writing Bytes • Below is the list of classes you use when you want to write bytes . OutputStream is an abstract class
  • 8. Reading Characters from a File • Say you want to read from a file: • You will need to open the file. • You will need to read from the file to the end . • You will need to close the file.
  • 9. • First of all, what is a file ? • A file is an instance of the class File import java.io; public class FileRead { public FileRead() { File inFile = new File( “Gavin King.txt” ); } public static void main( String[] args ) { FileRead fr = new FileRead(); } } Reading Characters from a File All the classes used in I/O come from this package.
  • 10. import java.io; public class FileRead { public FileRead() { try { File inFile = new File( “Gavin King.txt” ); } catch( IOException io ) { System.out.println( “IOException, io=“ + io ); } } public static void main( String[] args ) { FileRead fr = new FileRead(); } Because the constructor on File throws an IOException, we are forced to place it in a try-catch block Reading Characters from a File
  • 11. public class FileRead { public FileRead() { try { File inFile = new File( “infile.txt” ); File outFile = new File( “outFile.txt” ); FileReader fr = new FileReader( inFile ); FileWriter fw = new FileWriter( outFile ); int c = 0; boolean keepReading = true; while( keepReading ) { c = fr .read(); if( c == -1 )’ { keepReading = false; } else { fw .write( c ); } } fr.close(); fw.close(); } What is this? We read a character but store it as an integer? That’s right. Although we read an int , the FileWriter understands that it needs to write these as characters.
  • 12. Reading Bytes from a File • The approach for reading bytes is nearly the same. • The difference comes in the classes we choose to do the reading and writing.
  • 13. public class FileRead { public FileRead() { try { File inFile = new File( “inFile.txt” ); File outFile = new File( “outFile.txt” ); FileInputStream fis = new FileInputStream ( inFile ); FileOutputStream fos = new FileOutputStream ( outFile ); int c = 0; boolean keepReading = true; while( keepReading ) { c = fis.read(); if( c == -1 )’ { keepReading = false; } else { fos.write( c ); } } fr.close(); fw.close(); }
  • 14. Alternatives for Efficiency • As you can imagine, reading a byte or a character at a time is pretty inefficient. • For that reason, there are alternatives. • The best one is the BufferedReader . This class gathers a chunk of data at a read.
  • 15. public class FileRead { public FileRead() { try { File inFile = new File( “C:/orig/aFile.txt” ); File outFile = new File( “C:/final/outFile.txt” ); FileReader fr = new FileReader( inFile ); BufferedReader br = new BufferedReader ( fr ); FileWriter fw = new FileWriter( outFile ); BufferedWriter bw = new BufferedWriter ( fw ); String temp = null; boolean keepReading = true; while( keepReading ) { temp = br . readLine(); if( temp == null) { keepReading = false; } else { bw .write( temp ); } } br .close(); fr .close(); bw .close(); fw .close(); } Now, we have added a BufferedReader , which allows us to read a line at a time. The BufferedWriter also allows us to write an entire String
  • 16.  
  • 17.