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 |