File Handling in Java
Working with files in Java is challenging. There are a lot of libraries to import and a lot of objects to create.
Import the Library
Java requires several libraries to handle files. It is worth importing them all:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.Scanner;
Saving Data to a File
In most programming languages saving or retrieving data involves the following steps:
|
FileWriter fw = new FileWriter("Data.txt",true); // true - data will be appended to the end.
fw.write("hello"); fw.close(); |
Saving Data to a New Line
To write data to a new line you need to add a line separator to the string variable:
|
String myData "Hello";
myData +=System.getProperty("line.separator"); |
Deleting the File
Create a File object to delete the file:
File f = new File("Data.txt");
f.delete();
File f = new File("Data.txt");
f.delete();
Retrieving Data from a File
- You'll need to create a File object and then a Scanner object using the File object.
- You'll then need to loop through the file checking if there is another line of data.
- Once all data has been read you must close the file.
try
{
File df= new File("Data.txt");
Scanner rd= new Scanner(df);
while (rd.hasNextLine())
{
String s= rd.nextLine();
System.out.println(s);
}
myReader.close();
}
catch (FileNotFoundException e)
{
System.out.println("An error occurred.");
e.printStackTrace();
}