Java Review: Read, Write, and Delete Files

To create, write, and delete files, Java has some built in classes to help simplify things. To use these classes, we must create an object instance of them.

Create a file by using java.io.File class. Syntax:

java.io.File nameOfFile = new java.io.File( "folder/name.type" );

File has several useful methods. Syntax:

nameOfFile.exists(); : returns bool

.length(); : returns bytes

.getAbsolutePath(); : returns bool

.delete(); : returns bool, true is successfully deleted.

The File class can create a file and give details about it, but not really much else. We must use the java.io.PrintWriter to write to a file (add data) and java.util.Scanner is used to read a file.

To write to a file, or record data, we use the PrintWriter class. Syntax:

java.io.PrintWriter write = new PrintWriter(fileToUse);

Then we use it to print. Similar to console printing, we can now invoke our ‘write’ object with standard printing methods. Syntax:

write.print ("abc ");

write.printf(“The area is %2d ”, area);

Always remember to close the file to save everything properly. Syntax:

write.close();

Scanners can also take file names rather than System.in to read nextLine(), nextInt(), ect.

Syntax: {

java.util.Scanner read = new Scanner(“words.txt”);

              If all of these snippets were in a full main method, we would likely need to declare exceptions. When using parts of the java package, the return exception message could help share information further up the class hierarchy. So our main method declaration would need to inform the caller that input/output errors are common here because we may be writing or reading many types of data. Syntax:

Public static void main(String[] args) throws IOException {…}

Next
Next

Java Review: StringBuilder & StringBuffer