Institute of Computer Science
  1. Courses
  2. 2017/18 spring
  3. Object-Oriented Programming (Narva College) (P2NC.01.083)
ET
Log in

Object-Oriented Programming (Narva College) 2017/18 spring

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

Introduction

This chapter introduces one of Java's most important packages - java.io. Using the classes of java.io, it is possible to create, change, delete and rename files and folders.

The class File contains methods used for creating files or folders. The following statement new File("fileName") does not create a file yet, but an instance of the class File which would hold a reference to the file.

// 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").

Session 10
  • 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