Automation QA Testing Course Content

Handling Files in Java

File Handling:

file handling classes are available in java.io




for Reading/inputting the data to the program
1)FileInputStream
//creating object for File class..
File f=new File("filelocation");
//create object for FileInputStream
FileInputStream fs=new FileInputStream(f);
2)BufferedInputStream
BufferedInputStream bis=new BufferedInputStream(fs);
3)FileReader
4)BufferedReader
5)File

Methods:
1)read():it reads the byte data from file
2)readLine():it reads the data by line
3)nextLine():cursor goes to nextline
---------------------------------------------------------
1.While working with files, we need to handle the Checked Exception in our code, otherwise our code will not compile.

 2.FileReader class makes it possible to read the contents of a file as a stream of characters,
 thus we are using in our code to read characters from a text file.


FileReader fr = new FileReader(filePath)


 3.BufferedReader class provides buffering to our FileReader. Rather than reading one character at a time from the file,
 we read a larger block at a time using BufferedReader.



FileReader fr = new FileReader(filePath);
BufferedReader txtReader = new BufferedReader(fr);



We can specify the buffer size in the above case we have used the default size(8192 chars).
Incase we want sized buffer our code will look like this:-



Int bufferSize = 1000;
BufferedReader txtReader = new BufferedReader(fr, bufferSize);



 4.ReadLine, method of BufferedReader Class, which reads a line of text. A line is considered to be terminated by any one of a line feed
 ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

 Code:-

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class WorkingwithFiles {
 public static void main(String[] args) {
  //FilePath
  String sFilePath = "D:\\Automation\\Selenium\\TestFile.txt";
  //Creating FileReader object
  FileReader fr = null;
  //Creating BufferedReader object
  BufferedReader txtReader  = null;
  //Handling Exception using Try-Catch
    try {
     String sCurrentLine;
     fr =  new FileReader(sFilePath);
     txtReader = new BufferedReader(fr);

     //Reading file until file is null
     while ((sCurrentLine = txtReader.readLine())!= null) {
       System.out.println(sCurrentLine);
 
     } //while loop ending

    }catch(IOException e) {
         e.printStackTrace();
    } finally {
     try {
      if (txtReader != null)txtReader.close();
     } catch (IOException ex) {
      ex.printStackTrace();
     }
    }

   }
}
========================================================================


writing/outputting the data from program to files

1)FileOutputStream
FileOutputStream fos=new FileOutputStream(filelocation);
2)BufferedOutputStream
BufferedOutputStream bos=new BufferedOutputStream(fos);
3)FileWriter
4)BufferedWriter

Method:
write(char c):write the data from program to file
write(byte b)
flush()--to flush out the stream.
newLine();

-------------------------------------------------------------------------------------------
Important Tips for Writing into a File:-

 1.FileWriter class makes it possible to write a file as a stream of characters,
 same like FileReader above.


FileWriter fw = new FileWriter(filepath);


2.Incase we want to control whether to append or overwrite into text file


Boolean append = true;
FileWriter fw = new FileWriter(filepath, append);



By Default it is “False”, thus it will overwrite the existing data.

 3.BufferedWriter class provides buffering to our Write. Rather than write one character at a time
 to the file, we write a larger block at a time. This is typically much faster, especially for disk access and larger data amounts



FileWriter fw = new FileWriter(path)
BufferedWriter bw = new BufferedWriter(fw)


 We can control the size of bufferedwriter like we did in bufferedreader class

 4.We used File objects to obtain information about a file or directory.File object is used to obtain information about a particular file or directory and is not used to read or write data, like length of a file

Code:-


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;


public class WritingInFiles {
  public static void main(String[] args) {
   //Data to write
   String sContent = "Lets try to write newline into File";
  //FilePath
  String sFilePath = "D:\\Automation\\Selenium\\TestFile.txt";
   try {
                  //Creating File object
     File f = new File(sFilePath);
     // if file doesn't exists, then create it
     if(!f.exists()){
      f.createNewFile();
     }
     //Creating FileWriter object
     //using file object we got the filePath
     FileWriter fw = new FileWriter(f.getAbsoluteFile());
     //Creating BufferedWriter object
     BufferedWriter bw = new BufferedWriter(fw);
     //Writing content into file
     bw.write(sContent);
     //Adding new line
     bw.newLine();
     bw.close();
     System.out.println("Data is Successfully written");

    } catch (IOException e) {
     e.printStackTrace();
    }
   }

}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.