Docsity

Java IO: Writing and Reading Files using FileWriter and FileReader, Assignments of Programming Languages

Partial preview of the text

Download Java IO: Writing and Reading Files using FileWriter and FileReader and more Assignments Programming Languages in PDF only on Docsity!

CS212: OBJECT-ORIENTED

PROGRAMMING

Files & Streams

BASIC READ/ WRITE OPERATIONS USING IO PACKAGE

GENERAL PROCEDURE:  (^) General steps involved:

//For Reading:

  1. Open an InputStream
  2. While there is more information Read next data from stream
  3. Close the stream

//For Writing:

  1. Open an OutputStream
  2. While there is more information Write next data to stream
  3. Close the stream Open Close Read/Write

JAVA IO - CLASSES Character stream based classes

I. File Writer

II. File Reader

III. Buffered Reader

IV. Buffered Writer

WRITING TO A FILE FileWriter Class Constructors:  (^) 1. FileWriter ( String fileName)  (^) 2. FileWriter ( String fileName, boolean append)  (^) 3. FileWriter ( File file)  (^) 4. FileWriter ( File file, boolean append)

File f =new File("Path…");

f.createNewFile();

CREATING A NEW FILE WRITER

Method 1:

FileWriter writer1 = new FileWriter("path\to\your\

file1.txt");

Method 2:

File file = new File("path\to\your\file2.txt");

FileWriter writer2 = new FileWriter(file);

PERFORMING FILE IO-BASIC STRUCTURE

class FileWriterDemo {

void Method(){

try {

// File handling code

catch (IOException ex){

// In case of error this block executes

PERFORMING FILE IO- EXAMPLE public class fileHandlingBasics{ public void writeToFile(String path, String text){ //code to write to a file } public void readFromFile(String path){ //code to read from a file } }

READING FROM

A FILE

FILEREADER CLASS

FileReader class is used for reading streams of

characters from a file.

Constructors:

1. FileReader(String filePath)

2. FileReader(File fileObj)

READING FROM A FILE

TEST PROGRAM -READ

TEST PROGRAM-ADD MORE TEXT