Institute of Computer Science
  1. Courses
  2. 2019/20 spring
  3. Object-Oriented Programming (Narva College) (LTAT.NR.003)
ET
Log in

Object-Oriented Programming (Narva College) 2019/20 spring

  • Home
  • Materials
  • Grading
  • Java Glossary
  • Cheat sheet (S1-S6)
  • Source Example
  • Links
Chapter 9

Introduction

The Java I/O stream library is an important part of everyday programming. The stream API is overwhelmingly rich, replete with interfaces, objects, and methods to support almost every programmer's needs. On the other hand, it is easy to be lost among the stream implementation, especially for a beginner. This chapter shall try to provide some clue to streamline your understanding of java.io package. In short, the classes defined in the java.io package implement File, Input/Output Stream, and Serialization.

File class contains methods used for creating objects for files and folders. To convert a file or a folder name given as a string into a file object, use the following statement:

 File f = new File("fileName") 

After that it is possible to make different operations with the file or the folder:

// This program looks in the current folder for the files without extensions and adds the extensions
import java.io.File;

public class ChangeFileName {
  public static void main(String[] args) throws Exception {
    File dir = new File("."); // . means current folder
    String[] myFiles = dir.list();
    for (String f : myFiles) {
      File oldName = new File(f);
      if (oldName.isFile() && !f.contains(".")) {
        File newName = new File(f + ".txt");
        oldName.renameTo(newName);
        System.out.println("Files changed:  " + oldName.getName() + " -> " + newName.getName());
      }
    }
  }
}

Pay attention that Windows uses \ in the file's path and Mac/Linux systems use /. To make the code work on all systems, use the following notations: "someFolder" + File.separatorChar + "myFile" or new File("somefolder", "myFile").

Chapter 9
  • Institute of Computer Science
  • Faculty of Science and Technology
  • University of Tartu
In case of technical problems or questions write to:

Contact the course organizers with the organizational and course content questions.
The proprietary copyrights of educational materials belong to the University of Tartu. The use of educational materials is permitted for the purposes and under the conditions provided for in the copyright law for the free use of a work. When using educational materials, the user is obligated to give credit to the author of the educational materials.
The use of educational materials for other purposes is allowed only with the prior written consent of the University of Tartu.
Terms of use for the Courses environment