FILE MANAGEMENT IN JAVA
To work with files Java provides several classes that allow you to:
- create files and directories
- search files and directories
- rename files and directories
- delete files and directories
- write within a file
- read the text contained in a file
The main classes are found in the java.io package (io stands for InputOutput …) and are:
- For management:
- java.io.File
- for writing:
- java.io.FileWriter
- java.io.BufferedWriter
- java.io.PrintWriter
- for reading:
- java.io.FileReader
- java.io.BufferedReader
- File: is a representation of a file or directory. This class allows you to create, delete, rename, and search a file, directory (or subdirectory)
- FileWriter: allows you to write in a text file one character at a time
- BufferedWriter: is similar to the FileWriter class but allows characters in the file to be written in blocks, stored in a temporary buffer. Characters are read from the buffer and written to the file. This class has better performance than the FileWriter class.
- PrintWriter: is similar to the BufferedWriter class but allows you to write to the formatted text file
- FileReader: allows you to read the characters contained in a text file, reading them one at a time
- BufferedReader: is similar to the FileReader class but allows you to read the characters in the file in blocks, stored in a temporary buffer. When characters are requested, they are read from the buffer. This class has better performance than the FileReader class
THE FILE CLASS
The main constructor of the File class receives as input a variable of type String that contains the Path of the file(that is, the path where to save it and the name of the file or directory).
Examples of Path:
- “C:/courses/java/lessonX/”
- “C:/courses/java/lessonX/file1.txt”
The creation of the File class instance does not generate the physical creation of the file or directory on the hard disk.
- To create files physically, it is necessary to call the method createNewFile()
- To create directories physically, it is necessary to call the mkdir() method
The main methods of the File class are:
- exists(): returns true if the file or directory exists, false otherwise
- createNewFile(): creates a file on the disk in the specified Path
- delete(): deletes the file or directory from the disk
- isFile(): returns true if the resource is a file, false otherwise
- isDir(): returns true if the resource is a directory, false otherwise
- mkDir(): creates a directory on the disk in the specified Path
package it.corso.java.gestionefile; import java.io.File; import java.io.IOException; public class TestFileClass { public static void create()throws IOException{ //CREO IL PATH PER LA LA DIRECTORY File f1 = new File(new File(".").getCanonicalPath() + File.separator + "test-dir"); String dir = f1.getPath(); //PATH DEL FILE String file = dir + File.separator + "test-file.txt"; //CREO LA DIRECTORY creaDirectory(dir); //CREO IL FILE creaFile(file); //CREO I FILE PER LA LETTURA/SCRITTURA String file1 = dir + File.separator + "buffered-writer.txt"; creaFile(file1); String file2_1 = dir + File.separator + "file-writer.txt"; creaFile(file2_1); String file3 = dir + File.separator + "lettura.txt"; creaFile(file3); File d = new File(dir); System.out.println(d.isDirectory()); File f = new File(file); System.out.println(f.isFile()); File[] files = d.listFiles(); for (File file2 : files) { System.out.println(file2.getName()); } } public static void creaFile(String path) { File f = new File(path); if(!f.exists()) { try { f.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } } public static void creaDirectory(String path) { File d = new File(path); if(!d.exists()) { d.mkdir(); } } }
THE FILEWRITER CLASS
When we create an instance of the FileWriter class, the constructor must be passed an instance of the File class as input.
The main methods of the FileWriter class are:
- write(String str): writes the string str into the file
- close(): closes the stream on the file
- flush(): ensures that all text has been written to the file
THE BUFFEREDWRITER CLASS
The FileWriter class, as we said, writes a single character at a time. The BufferedWriter class allows you to write to files more efficiently than the FileWriter class. When we create an instance of the BufferedWriter class, the constructor must be passed an instance of the FileWriter class as input.
The main methods of the BufferedWriter class are:
- write(String str): writes the string str into the file
- newLine(): creates a new line in the file. Text following this instruction is written on a new line.
- close(): closes the stream on the file
- flush(): ensures that all text has been written to the file
package it.corso.java.gestionefile; import java.io.*; public class WriteClassFile { public static void write() { try { String dir = new File(new File(".").getCanonicalPath() + File.separator + "test-dir").getPath(); esempioBufferedFileWriter(dir + File.separator + "buffered-writer.txt", new String[]{"Marco", "Albasini", "Corso Java", "Avanzato!"}); esempioFileWriter(dir + File.separator + "file-writer.txt", new String("Corso Java avanzato")); } catch(IOException e) { e.printStackTrace(); } } public static void esempioPrintWriter(String filePath, String[] testo) { PrintWriter pw = null; try { pw = new PrintWriter(new FileWriter(getFile(filePath))); for (String string : testo) { pw.write(string); } } catch (IOException e) { e.printStackTrace(); } finally { pw.close(); } } public static void esempioBufferedFileWriter(String filePath, String[] testo) { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(getFile(filePath))); for (String string : testo) { bw.write(string); bw.newLine(); } } catch (IOException e) { e.printStackTrace(); } finally { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void esempioFileWriter(String filePath, String testo) { FileWriter fw = null; try { fw = new FileWriter(getFile(filePath)); fw.write(testo); } catch (IOException e) { e.printStackTrace(); } finally { try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } private static File getFile(String filePath) { File file = new File(filePath); if(!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } return file; } }
THE FILEREADER CLASS
When we create an instance of the FileReader class, the constructor must be passed an instance of the File class as input. The main methods of the FileReader class are:
- read(char[]): reads a finite number of characters, one at a time, and stores them in the char array passed as input
- close(): closes the stream from the file.
THE BUFFEREDREADER CLASS
The BufferedReader class allows reading from a file more efficiently than the FileReader class, which reads a single character at a time. When we create an instance of the BufferedReader class, the constructor must be passed an instance of the FileReader class as input. The main methods of the BufferedReader class are:
- read(char[]): reads a finite number of characters, one at a time, and stores them in the char array passed as input
- close(): closes the stream from the file
package it.corso.java.gestionefile; import java.io.*; public class ReadClassFile { public static void read(){ try { String dir = new File(new File(".").getCanonicalPath() + File.separator + "test-dir").getPath(); esempioFileReader(dir + File.separator + "lettura.txt"); esempioBufferedReader(dir + File.separator + "lettura.txt"); } catch(IOException ex){ ex.printStackTrace(); } } public static void esempioBufferedReader(String filePath) { File f = new File(filePath); if(f.exists()) { BufferedReader fr = null; try { fr = new BufferedReader(new FileReader(f)); char[] testo = new char[1024]; int size = fr.read(testo); for(int i = 0; i < size; i++) { System.out.print(testo[i]); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void esempioFileReader(String filePath) { File f = new File(filePath); if(f.exists()) { FileReader fr = null; try { fr = new FileReader(f); char[] testo = new char[1024]; int size = fr.read(testo); for(int i = 0; i < size; i++) { System.out.print(testo[i]); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
LINKS TO PREVIOUS POSTS
LINK TO CODE ON GITHUB
EXECUTION OF THE EXAMPLE CODE
- Download the code from GITHUB, launch the JAR file with the following command in Visual Studio Code, locating in the directory containing the JAR.
java -jar –enable-preview CorsoJava.jar
- Or run the main found in the file CorsoJava.java.
Leave A Comment