SlideShare a Scribd company logo
Lecture 11
File IO operations in Java




                Object Oriented Programming
                Eastern University, Dhaka
                        Md. Raihan Kibria
List all files/folders under a
                 directory
import java.io.File;

public class DirDemo {

    static final String DIR_NAME = "/home/user";

    public static void main(String[] args) {
      File file = new File(DIR_NAME);
      String[] files = file.list();
      for (String f : files){
        System.out.println(f);
      }
    }
}




    java.io.File is the class of interest
Output
oop_lecture1.ppt
oop_lecture7.ppt
oop_lecture9_10.ppt
oop_lecture9.ppt
oop_lecture3.ppt
com
oop_lecture9_11.ppt
oop_lecture4.ppt
oop_lecture6.ppt
oop_lecture5.ppt
oop_lecture8.ppt
How many are folders and how
    many are files under a directory
public class FileDirCheckDemo {

 static final String DIR_NAME = "/home/user";

  public static void main(String[] args) {
    File file = new File(DIR_NAME);
    String[] files = file.list();
    int countOfDir = 0;
    int countOfFile = 0;
    for (String f : files){
    File fileReal = new File(DIR_NAME + File.separator + f);
    if (fileReal.isDirectory())
         countOfDir++;
    else
         countOfFile++;
    }
    System.out.println("No of directories: " + countOfDir + "; no of
files: " + countOfFile);
  }
}     Output:

      No of directories: 2; no of files: 18
Other useful methods on File

Create a new File:
          File f = new File("D:tempnewfile.txt");
          f.createNewFile();

Delete a File:
          File f = new File("D:tempnewfile.txt");
          f.delete();

Rename a File:
        File f = new File("D:tempnewfile.txt");
        File renF = new File("D:tempnewfile.txt");
        f.renameTo(renF);
Copy a file to another
public class FileDemo {

    static final String FIRST_FILE_NAME= "/home/user/raihan_fb.png";
    static final String SECOND_FILE_NAME = "/home/user/out.png";

    public static void main(String[] args) {
      try{
           File file1 = new File(FIRST_FILE_NAME);
           File file2 = new File(SECOND_FILE_NAME);

            byte[] b = new byte[1024];
            FileInputStream fis = new FileInputStream(file1);
            FileOutputStream fos = new FileOutputStream(file2);
            int len = 0;
            while ((len = fis.read(b)) != -1){
                fos.write(b, 0, len);
            }
            fis.close();
            fos.close();
        }catch(Exception e){

        }
    }
}
Reading a text file and output to
                 console
public class ReadTextDemo {

    static final String FILE_NAME =   "/home/user/test.txt";

    public static void main(String[] args) {
      File file = new File(FILE_NAME);
      try{
        BufferedReader br = new BufferedReader(new FileReader(file));
        String s = null;
        while ( (s = br.readLine()) != null){
           System.out.println(s);
        }
        br.close();
      }catch(Exception e){
        e.printStackTrace();
      }
    }
}
Output

text.txt:                Console output:



Apples are red           Apples are red
                         Coconuts are green
Coconuts are green       Grapes are sour
Grapes are sour
Interface revisited
     Two utility methods

public class InterfaceDemo {

    static final String FILE_NAME = "/home/user/data.txt";

    public static int getTotalVolume(List<Volume>items){
      int total = 0;
      for (Volume v : items){
        total += v.getVolume();
      }
      return total;
    }

    public static int getTotalWeight(List<Weight>items){
      int total = 0;
      for (Weight w : items){
        total += w.getWeight();
      }
    return total;
}
public static void main(String[] args) {
  List<Volume>vols = new ArrayList<Volume>();
  List<Weight>wts = new ArrayList<Weight>();
  File file = new File(FILE_NAME);
  try{
    BufferedReader br = new BufferedReader(new FileReader(file));
    String s = null;
    while ( (s = br.readLine()) != null){
       String[] split = s.split(",");
       if (split[0].equals("Book")){
         Book book = new Book();
         book.width = Integer.parseInt(split[1]);
         book.height = Integer.parseInt(split[2]);
         book.depth = Integer.parseInt(split[3]);
         vols.add(book);
         wts.add(book);
       }else {
         Container c = new Container();
         c.radius = Integer.parseInt(split[1]);
         c.height = Integer.parseInt(split[2]);
         vols.add(c);
         wts.add(c);
       }
    }
    br.close();

      System.out.println("Total volume: " + getTotalVolume(vols));
      System.out.println("Total weight: " + getTotalWeight(wts));
    }catch(Exception e){
      e.printStackTrace();
    }
}
}
Two interfaces
       interface Volume{
         int getVolume();
       }

       interface Weight{
         int getWeight();
       }

data.txt:


Book,10,20,3
Book,20,40,2
Container,20,40
Container,30,50
class   Book implements Volume, Weight{
  int   id;
  int   width;
  int   height;
  int   depth;

    public int getVolume() {
      return width * height * depth;
    }

    public int getWeight() {
      return getVolume() * 2;
    }
}

class   Container implements Volume, Weight{
  int   id;
  int   radius;
  int   height;

    public int getVolume() {
      return (int)(Math.PI * radius * radius * height);
    }

    public int getWeight() {
      return getVolume() * 5;
    }
}
Output
Total volume: 193836
Total weight: 962580
Lessons learned

Polymorphism: an object can take more than
 one forms. For example, getTotalVolume()
 sees the items as of type Volume;
 getTotalWeight() sees the items as of type
 Weight

More Related Content

PDF
Python - File operations & Data parsing
PPTX
Python IO
PPT
File handling(some slides only)
PDF
File and directories in python
PPT
Java File I/O
PPT
Unit5 C
PPT
File in cpp 2016
PPTX
Pf cs102 programming-8 [file handling] (1)
Python - File operations & Data parsing
Python IO
File handling(some slides only)
File and directories in python
Java File I/O
Unit5 C
File in cpp 2016
Pf cs102 programming-8 [file handling] (1)

What's hot (20)

PDF
File handling
PPT
PPSX
Files in c++
PPT
17 files and streams
PPT
File handling
DOCX
File handling in c++
PPT
file handling, dynamic memory allocation
PPTX
Files and file objects (in Python)
PPT
Cpp file-handling
PPT
Files in c++ ppt
PPT
File handling in C++
PDF
C++ Files and Streams
PPT
File handling in_c
PPTX
Filesin c++
PPTX
File Handling Python
PPT
cpp-file-handling
PDF
I/O in java Part 1
PPT
Java Input Output and File Handling
PPTX
basics of file handling
File handling
Files in c++
17 files and streams
File handling
File handling in c++
file handling, dynamic memory allocation
Files and file objects (in Python)
Cpp file-handling
Files in c++ ppt
File handling in C++
C++ Files and Streams
File handling in_c
Filesin c++
File Handling Python
cpp-file-handling
I/O in java Part 1
Java Input Output and File Handling
basics of file handling
Ad

Viewers also liked (9)

PPT
Oop lecture9 13
PDF
Presentacion viernes 20 [compatibility mode]
PPT
Oop lecture9 12
PPT
Oop lecture8
PPT
Oop lecture2
DOCX
Calendario portada
PPT
Oop lecture1
PPTX
Cwgd
PPT
Oop lecture6
Oop lecture9 13
Presentacion viernes 20 [compatibility mode]
Oop lecture9 12
Oop lecture8
Oop lecture2
Calendario portada
Oop lecture1
Cwgd
Oop lecture6
Ad

Similar to Oop lecture9 11 (20)

PPTX
File Input and output.pptx
PPTX
Understanding java streams
PPTX
File Handlingb in java. A brief presentation on file handling
PDF
5java Io
PPT
file handling in object oriented programming through java
PDF
[10] Write a Java application which first reads data from the phoneb.pdf
DOCX
FileHandling.docx
PPTX
chapter 2(IO and stream)/chapter 2, IO and stream
PDF
Java Day-6
PPS
Files & IO in Java
DOC
Inheritance
PPTX
File Handling in Java Oop presentation
DOCX
Discussion Board 2William Denison27 NOV 2014A Java class t.docx
DOCX
Discussion Board 2William Denison27 NOV 2014A Java class t.docx
PPTX
PDF
Sam wd programs
PPTX
File Handling.pptx
PPT
Comp102 lec 11
PPT
Chapter 12 - File Input and Output
PPT
Java căn bản - Chapter12
File Input and output.pptx
Understanding java streams
File Handlingb in java. A brief presentation on file handling
5java Io
file handling in object oriented programming through java
[10] Write a Java application which first reads data from the phoneb.pdf
FileHandling.docx
chapter 2(IO and stream)/chapter 2, IO and stream
Java Day-6
Files & IO in Java
Inheritance
File Handling in Java Oop presentation
Discussion Board 2William Denison27 NOV 2014A Java class t.docx
Discussion Board 2William Denison27 NOV 2014A Java class t.docx
Sam wd programs
File Handling.pptx
Comp102 lec 11
Chapter 12 - File Input and Output
Java căn bản - Chapter12

More from Shahriar Robbani (8)

PPTX
PPT
Oop lecture9 10
PPT
Oop lecture4
PPT
Oop lecture9
PPT
Oop lecture7
PPT
Oop lecture5
PPT
Oop lecture3
Oop lecture9 10
Oop lecture4
Oop lecture9
Oop lecture7
Oop lecture5
Oop lecture3

Recently uploaded (20)

PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Classroom Observation Tools for Teachers
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Pharma ospi slides which help in ospi learning
PDF
Insiders guide to clinical Medicine.pdf
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Cell Types and Its function , kingdom of life
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
102 student loan defaulters named and shamed – Is someone you know on the list?
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Classroom Observation Tools for Teachers
Microbial diseases, their pathogenesis and prophylaxis
Pharma ospi slides which help in ospi learning
Insiders guide to clinical Medicine.pdf
01-Introduction-to-Information-Management.pdf
Renaissance Architecture: A Journey from Faith to Humanism
VCE English Exam - Section C Student Revision Booklet
Cell Types and Its function , kingdom of life
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
STATICS OF THE RIGID BODIES Hibbelers.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Supply Chain Operations Speaking Notes -ICLT Program
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025

Oop lecture9 11

  • 1. Lecture 11 File IO operations in Java Object Oriented Programming Eastern University, Dhaka Md. Raihan Kibria
  • 2. List all files/folders under a directory import java.io.File; public class DirDemo { static final String DIR_NAME = "/home/user"; public static void main(String[] args) { File file = new File(DIR_NAME); String[] files = file.list(); for (String f : files){ System.out.println(f); } } } java.io.File is the class of interest
  • 4. How many are folders and how many are files under a directory public class FileDirCheckDemo { static final String DIR_NAME = "/home/user"; public static void main(String[] args) { File file = new File(DIR_NAME); String[] files = file.list(); int countOfDir = 0; int countOfFile = 0; for (String f : files){ File fileReal = new File(DIR_NAME + File.separator + f); if (fileReal.isDirectory()) countOfDir++; else countOfFile++; } System.out.println("No of directories: " + countOfDir + "; no of files: " + countOfFile); } } Output: No of directories: 2; no of files: 18
  • 5. Other useful methods on File Create a new File: File f = new File("D:tempnewfile.txt"); f.createNewFile(); Delete a File: File f = new File("D:tempnewfile.txt"); f.delete(); Rename a File: File f = new File("D:tempnewfile.txt"); File renF = new File("D:tempnewfile.txt"); f.renameTo(renF);
  • 6. Copy a file to another public class FileDemo { static final String FIRST_FILE_NAME= "/home/user/raihan_fb.png"; static final String SECOND_FILE_NAME = "/home/user/out.png"; public static void main(String[] args) { try{ File file1 = new File(FIRST_FILE_NAME); File file2 = new File(SECOND_FILE_NAME); byte[] b = new byte[1024]; FileInputStream fis = new FileInputStream(file1); FileOutputStream fos = new FileOutputStream(file2); int len = 0; while ((len = fis.read(b)) != -1){ fos.write(b, 0, len); } fis.close(); fos.close(); }catch(Exception e){ } } }
  • 7. Reading a text file and output to console public class ReadTextDemo { static final String FILE_NAME = "/home/user/test.txt"; public static void main(String[] args) { File file = new File(FILE_NAME); try{ BufferedReader br = new BufferedReader(new FileReader(file)); String s = null; while ( (s = br.readLine()) != null){ System.out.println(s); } br.close(); }catch(Exception e){ e.printStackTrace(); } } }
  • 8. Output text.txt: Console output: Apples are red Apples are red Coconuts are green Coconuts are green Grapes are sour Grapes are sour
  • 9. Interface revisited Two utility methods public class InterfaceDemo { static final String FILE_NAME = "/home/user/data.txt"; public static int getTotalVolume(List<Volume>items){ int total = 0; for (Volume v : items){ total += v.getVolume(); } return total; } public static int getTotalWeight(List<Weight>items){ int total = 0; for (Weight w : items){ total += w.getWeight(); } return total; }
  • 10. public static void main(String[] args) { List<Volume>vols = new ArrayList<Volume>(); List<Weight>wts = new ArrayList<Weight>(); File file = new File(FILE_NAME); try{ BufferedReader br = new BufferedReader(new FileReader(file)); String s = null; while ( (s = br.readLine()) != null){ String[] split = s.split(","); if (split[0].equals("Book")){ Book book = new Book(); book.width = Integer.parseInt(split[1]); book.height = Integer.parseInt(split[2]); book.depth = Integer.parseInt(split[3]); vols.add(book); wts.add(book); }else { Container c = new Container(); c.radius = Integer.parseInt(split[1]); c.height = Integer.parseInt(split[2]); vols.add(c); wts.add(c); } } br.close(); System.out.println("Total volume: " + getTotalVolume(vols)); System.out.println("Total weight: " + getTotalWeight(wts)); }catch(Exception e){ e.printStackTrace(); } } }
  • 11. Two interfaces interface Volume{ int getVolume(); } interface Weight{ int getWeight(); } data.txt: Book,10,20,3 Book,20,40,2 Container,20,40 Container,30,50
  • 12. class Book implements Volume, Weight{ int id; int width; int height; int depth; public int getVolume() { return width * height * depth; } public int getWeight() { return getVolume() * 2; } } class Container implements Volume, Weight{ int id; int radius; int height; public int getVolume() { return (int)(Math.PI * radius * radius * height); } public int getWeight() { return getVolume() * 5; } }
  • 14. Lessons learned Polymorphism: an object can take more than one forms. For example, getTotalVolume() sees the items as of type Volume; getTotalWeight() sees the items as of type Weight