• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Introduction to Computer Science

Module 14. File I/O

Many software applications may require interaction with the file system to read or permanently store data on the machine. In this module, we will describe how files can be accessed in our Java programs.

Files in Java

Exercise 1: Accessing files

Using the information presented in the previous section, write a Java program that can create a File object to refer to a file that is stored in a given path. Using the File class methods, print the properties of this file including its path, file name, size and the last date it was modified.

Solution

Reading files

Exercise 2: Reading files

In this exercise, we can similarly create a File object referring to a given file in the file system, and further use the Scanner class methods to read the contents of the file. Please create a file with the given contents and print them inside your Java method.

Solution

We can implement a Java method that iterates through the lines of the file with the nextLine() method in the Scanner class.

Note that if we wanted to read each word separately, we could also use the next() method, which is sensitive to white space.

Writing to Files

Exercise 3: Writing to files

Let’s now try to practice writing to files using the FileWriter class in Java. You can create a File object referring to your output file destination, and use the write() method from the FileWriter class to write any text content into the output file.

Solution

 

Primary Sidebar

List of Contents

  • Course Description
  • Module 1. Introduction to Computers and Programming
  • Module 2. The Java language
  • Module 3. Variables and Data Types
  • Module 4. Logical expressions and conditional executing
  • Module 5. Characters and Strings
  • Module 6. Loops
  • Module 7. Arrays
  • Module 8. Methods
  • Module 9. Introduction to the Object-Oriented Programming Paradigm
  • Module 10. Classes and Objects
  • Module 11. Inheritance and Polymorphism
  • Module 12. Interfaces and Abstract Classes
  • Module 13. Exception handling
  • Module 14. File I/O
  • Module 15. Recursion
  • Instructions for software installation
  • Self-assessment quizzes

Footer

This website has been created by Duygu Ataman, Devesh Devendra and Akash Harikrishanan. We thank New York University professors Craig Kapp, Anasse Bari and Gizem Kayar for sharing their feedback and resources to implement a successful online learning platform.

Contact

E-mail: ataman@nyu.edu

www.duyguataman.com

Dr. Duygu Ataman

Assistant Professor and Faculty Fellow, Courant Institute for Mathematical Sciences

Copyright © 2026 · eleven40 Pro on Genesis Framework · WordPress · Log in