diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 63621ae..89909cb 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -440,7 +440,7 @@ public class CreateFile {
- Finally, we will take a look at using Java to delete files. This one is pretty straight-forward and follows the structure used to create files. This time, however, try/catch blocks are not needed for the program to compile. First, the CreateFile class from before will be used to create a file:
+ Lastly, we will take a look at using Java to delete a file. This is pretty straight-forward and follows the structure used to create files. Here is the
- The next example is Python code that can be used to delete files. This code cannot be run because importing
- And finally, we have Java code that deletes files. We will call this class DeleteFile:
+ And finally, we have Java code that deletes a file. We will call this class
- import java.io.File;
-
- public class DeleteFile {
- public static void main(String[] args) {
- File myFile = new File("myfile.txt");
- if (myFile.delete()) {
- System.out.println("Deleted " + myFile.getName());
- } else {
- System.out.println("File could not be deleted.");
- }
- }
+import java.io.File;
+import java.io.IOException;
+
+public class DeleteFile {
+ public static void main(String[] args) {
+ try {
+ File myFile = new File("myfile.txt");
+
+ // Create the file (does nothing if it already exists)
+ myFile.createNewFile();
+ System.out.println("File created: " + myFile.getName());
+
+ // Delete the file
+ if (myFile.delete()) {
+ System.out.println("Deleted " + myFile.getName());
}
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+}
+
- This is almost identical to the code within the try block of the CreateFile class we made earlier. The main difference is the use of the