![]() | 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 | ![]() |

