Core Java - SPLessons

File Handling in Java

Home > Lesson > Chapter 32
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

File Handling in Java

File Handling in Java

shape Introduction

File Handling in Java, Every Java class needs inputs and outputs are available in java.io package, to handle the data Java uses streams concept, to handle the data, developer has to concentrate on two things, they are input stream and output stream. Following are the file handling classes.

shape Conceptual figure

File Handling in Java, following is the conceptual figure which describes file handling concept.

Input/Output

shape Description

File Handling in Java, Java Input and Output is used to process the input and produce the output based on the input.Java uses the concept of stream to make I/O operation fast. A stream is a sequence of data. Streams support many different kinds of data, including bytes, primitive data types, characters, and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways.

Character Streams

shape Description

File Handling in Java, Java Character streams are used to perform input and output for 16-bit unicode. There are many classes related to character streams but the most frequently used classes are FileReader and FileWriter.

shape Example

[java] package com.spl.file; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class Writer { static FileWriter file; public static void main(String[] args) { System.out.println("Program starts"); try { file=new FileWriter("E:\\SPL\\sample.txt"); file.write("Welcome "); file.write("to SPLessons"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { file.flush(); file.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("Program ends"); } } [/java] Output: When compile the code result will be as follows.

shape Example

[java] package com.spl.file; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class Reader { public static void main(String[] args) { System.out.println("Program starts"); try { FileReader read=new FileReader("E:\\SPL\\sample.txt"); File fileInt=new File("E:\\SPL\\sample.txt"); int totalChar=(int) fileInt.length(); char[] data=new char[totalChar]; read.read(data); String str=new String(data); System.out.println(str); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Program ends"); } } [/java] Output: When compile the code result will be as follows. [c] Program starts Welcome to SPLessons Program ends [/c]

Byte Streams

shape Description

File Handling in Java, Java byte streams are used to perform input and output of 8-bit bytes. There are many classes related to byte streams but the most frequently used classes are FileInputStream and FileOutputStream.

shape Example

[java] package com.spl.file; import java.io.FileOutputStream; import java.io.IOException; public class FileOutput { private static final String OUTPUT_FILE = "E:\\SPL\\sample.txt"; public static void main(String[] args) { System.out.println("Program starts"); String content = "Welcome to SPLessons="; byte[] bytes = content.getBytes(); try (FileOutputStream out = new FileOutputStream(OUTPUT_FILE)) { // write a byte sequence out.write(bytes); // write a single byte // out.write(bytes[0]); // write sub sequence of the byte array out.write(bytes,4,9); } catch (IOException e) { e.printStackTrace(); } System.out.println("Program ends"); } } [/java] Output: When compile the code result will be as follows.

shape Example

[java] package com.spl.file; import java.io.FileInputStream; public class FileInput { private static final String OUTPUT_FILE = "E:\\SPL\\sample.txt"; public static void main(String[] args) { System.out.println("Program starts"); try{ FileInputStream fin=new FileInputStream(OUTPUT_FILE); int i=0; while((i=fin.read())!=-1){ System.out.println((char)i); } fin.close(); }catch(Exception e){ System.out.println(e); } System.out.println("Program ends"); } } [/java] Output: When compile the code result will be as follows. [c] Program starts W e l c o m e t o S P L e s s o n s Program ends[/c]

Buffered Streams

shape Description

File Handling in Java, Buffered input streams read data from a memory area known as a buffer. The native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.There are many classes related to byte streams but the most frequently used classes are BufferedReader and BufferedWriter. These are thread safe and efficient than File Reader and Writer.

shape Examples

[java] package com.spl.file; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class BufferedWriterEx { public static void main(String[] args) { System.out.println("Program starts"); try { String content = "This is an example"; File file = new File("E:\\SPL\\sample.txt"); // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Program ends"); } } [/java] Output: When compile the code result will be as follows.

shape Examples

[java] package com.spl.file; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferedReaderEx { public static void main(String[] args) { System.out.println("Program starts"); BufferedReader br = null; try { String sCurrentLine; br = new BufferedReader(new FileReader("E:\\SPL\\sample.txt")); while ((sCurrentLine = br.readLine()) != null) { System.out.println(sCurrentLine); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null)br.close(); } catch (IOException ex) { ex.printStackTrace(); } } System.out.println("Program ends"); } } [/java] Output: When compile the code result will be as follows. [c] Program starts This is an example Program ends [/c]

Standard Streams

shape Description

Java provides following three standard streams
  • Standard Input: This is used to input the data to user's program and a keyboard is used as standard input stream and represented as System.in .
  • Standard Output: This is used to output the data produced by the user's program and a computer screen is used to standard output stream and represented as System.out.
  • Standard Error: This is used to output the error data produced by the user's program and a computer screen is used to standard error stream and represented as System.err.
  • shape Example

    [java] package com.spl.file; import java.util.Scanner; public class ScannerEx { public static void main(String args[]){ System.out.println("Program starts"); Scanner sc=new Scanner(System.in); System.out.println("Enter your number"); int rollno=sc.nextInt(); System.out.println("Enter your string"); String name=sc.next(); System.out.println("Enter your double"); double fee=sc.nextDouble(); System.out.println("number:"+rollno+" string:"+name+" double:"+fee); sc.close(); System.out.println("Program ends"); } } [/java] Output: When compile the code result will be as follows. [c] Program starts Enter your number 123 Enter your string splessons Enter your double 1489.78 number:123 string:splessons double:1489.78 Program ends[/c]

    Creating temporary file

    The following is an example to create a temporary file. [java]package com; import java.io.*; public class Main { public static void main(String[] args) throws Exception { File temp = File.createTempFile ("pattern", ".suffix"); temp.deleteOnExit(); BufferedWriter out = new BufferedWriter (new FileWriter(temp)); out.write("aString"); System.out.println("temporary file created"); out.close(); } }[/java] In the above example, createTempFile() method creates a new empty file in the specified directory where as deleteOnExit() method is called to delete the file created by this method. Output: Now the result will be as follows. [c]temporary file created[/c]

    Summary

    shape Key Points

  • The flush() method flushes the characters from a write buffer to the character.
  • The printf() is used to format the string.