Files Read & Write

From Java Programming II
Jump to: navigation, search

Reading From and Writing To Files in Java

Learning Outcomes

  • Read from a file in java using Scanner class
  • Write to a file in Java using the FileWriter class in either Write mode or Append mode
  • Get a reference object to a file using the File class
  • Process a String line in a file using the method split().

Video Tutorial

Code

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class FileProcessing {
   public static void main(String [] args) throws FileNotFoundException, IOException {
       
       String inputFileName = "student.txt";
       String outputFileName = "output.txt";
       
       //create a file object
       File inputFile = new File(inputFileName);
       File outputFile = new File(outputFileName);
        
       //create a scanner object that opens up the file
       Scanner input = new Scanner(inputFile);
        
       //create a FileWriter object to write into the file
       FileWriter fw = new FileWriter (outputFile, false);
 
       
       int count=0;
       //process the file
       while (input.hasNext()){
          String line = input.nextLine(); 
          count++;
          String [] lineArray = line.split(":");
          for (String s : lineArray){
           System.out.print(s+" ");
       }
       System.out.println();
       }  
        fw.write("the number of students is " + count+"\n");  
        fw.close();
        input.close();
   }
}

Using FileInputStream and FileOutputStream


Using BufferedReader