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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Destaque

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
 

Destaque (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
 

Semelhante a 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
 

Último

Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxNikitaBankoti2
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 

Último (20)

Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 

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.