#8-FileHandling

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Java Read Files Use the Scanner class to read the contents of the text file:

// Import the File class import java.io.File; // Import this class to handle errors import java.io.FileNotFoundException; // Import the Scanner class to read text files import java.util.Scanner; public class ReadFile { public static void main(String[] args) { try { File myObj = new File("filename.txt"); Scanner myReader = new Scanner(myObj); while (myReader.hasNextLine()) { String data = myReader.nextLine(); System.out.println(data); } myReader.close(); } catch (FileNotFoundException e) { System.out.println("An error occurred."); e.printStackTrace(); } } } // Files in Java might be tricky, but it is fun enough!

To use the java.io File class:

Create an object of the class, and specify the filename or directory name: // Import the File class import java.io.File; // Specify the filename File myObj = new File("filename.txt");

Java File Handling

File handling is an important part of any application. Java has several methods for creating, reading, updating, and deleting files.

What are some of the classes in the Java API used to read and write files in Java:

FileReader, BufferedReader, Files, Scanner, FileInputStream, FileWriter, BufferedWriter, FileOutputStream, etc. Which one to use depends on the Java version you're working with whether you need to read bytes or characters, and size of file/lines etc.

The File class has many useful methods for creating and getting information about files. List and define some of the messages:

Method Type Description canRead() Boolean Tests whether the file is readable or not canWrite() Boolean Tests whether the file is writable or not createNewFile() Boolean Creates an empty file delete() Boolean Deletes a file exists() Boolean Tests whether the file exists getName() String Returns the name of the file getAbsolutePath() String Returns the absolute pathname of the file length() Long Returns the size of the file in bytes list() String[] Returns an array of the files in the directory mkdir() Boolean Creates a directory

To create a file in a specific directory (requires permission) how is this done?

Specify the file path and use "\\" to escape the "\" character (for Windows). File myObj = new File("C:\\Users\\MyName\\filename.txt"); On Mac and Linux just write the path, like: /Users/name/filename.txt File myObj = new File("/Users/name/filename.txt");

How do we work with files in java?

The File class from the java.io package, allows us to work with files.

Java Delete Files

To delete a file in Java, use the delete() method: // Import the File class import java.io.File; public class DeleteFile { public static void main(String[] args) { File myObj = new File("filename.txt"); if (myObj.delete()) { System.out.println("Deleted the file: " + myObj.getName()); } else { System.out.println("Failed to delete the file."); } } } // Deleted the file: filename.txt // Delete a Folder

Get File Information

To get more information about a file, use any of the File methods: getName() getAbsolutePath() canWrite() canRead() length() // Import the File class import java.io.File; public class GetFileInfo { public static void main(String[] args) { File myObj = new File("filename.txt"); if (myObj.exists()) { System.out.println("File name: " + myObj.getName()); System.out.println("Absolute path: " + myObj.getAbsolutePath()); System.out.println("Writeable: " + myObj.canWrite()); System.out.println("Readable " + myObj.canRead()); System.out.println("File size in bytes " + myObj.length()); } else { System.out.println("The file does not exist."); } } } // File name: filename.txt // Absolute path: C:\Users\MyName\filename.txt // Writeable: true // Readable: true // File size in bytes: 0

How do you write To a File:

Use the FileWriter class and its write() method to write text to the file (when done writing to the file, close it with the close() method) // Import the FileWriter class import java.io.FileWriter; // Import the IOException class to handle errors import java.io.IOException; public class WriteToFile { public static void main(String[] args) { try { FileWriter myWriter = new FileWriter("filename.txt"); myWriter.write("Files in Java might be tricky, but it is fun enough!"); myWriter.close(); System.out.println("Successfully wrote to the file."); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } } // Successfully wrote to the file.

Java Create and Write To Files To create a file in Java, you can use the:

createNewFile() method. Returns a boolean value: true if file is created, false if it exists.

You can delete a folder in Java but it must be empty:

import java.io.File; public class DeleteFolder { public static void main(String[] args) { File myObj = new File("C:\\Users\\MyName\\Test"); if (myObj.delete()) { System.out.println("Deleted the folder: " + myObj.getName()); } else { System.out.println("Failed to delete the folder."); } } } // Deleted the folder: Test

The createNewFile() method is enclosed in a try...catch block. This is necessary because:

it throws an IOException if an error occurs (file can't be created) declare myObj and create "file.txt" using the file class: // Import the File class import java.io.File; // Import the IOException class to handle errors import java.io.IOException; public class CreateFile { public static void main(String[] args) { try { File myObj = new File("filename.txt"); if (myObj.createNewFile()) { System.out.println("File created: " + myObj.getName()); } else { System.out.println("File already exists."); } } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } } // File created: filename.txt


Ensembles d'études connexes

NSG 330 Ch 69- Management Neurologic Infections, Autoimmune Disorders, Neuropathies

View Set

Health Assessment Week 5 Musculoskeletal Assessment

View Set

Speciation I - Biology II Assignment

View Set

WEEK 1-3 QUIZ 1 MED SURG 2 PREP U

View Set

Chapter 3: Field & Home Office Underwriting & Policy Insurance

View Set

Social Issues in Contemporary Society Unit 1

View Set