Learning Java/File IO
File input/output is quite similar to the System.in and System.out that you already have begun using In Java, files can be represented by the class java.io.File.
Imports
[edit | edit source]To use the objects presented in this section please add
import java.io.*;
import java.util.Scanner;
To the top of your .java file.
Files
[edit | edit source]Files are another type of variable. You can make a file like this:
File f = new File("test.txt")
This does not return an exception if the file doesn't exist. To check if it does:
f.exists()
This will return a boolean.
To check if it is a file or directory:
f.isFile()
f.isDirectory()
For a full list of methods you can use, go to File (Java 8 documentation).
File Output
[edit | edit source]To write to a file, you can use a FileWriter or a FileOutputStream.
FileWriter
[edit | edit source]This class writes strings or char[] to a file. To create one:
FileWriter fw = new FileWriter("test.txt");//Create a filewriter writing to test.txt
FileWriter fw = new FileWriter("test.txt", true);//Do not delete contents of file - append to the end
It is as simple to write. After you create a FileWriter you can write strings to that file:
String s = "Testing";
fw.write(s);
After you're done with your FileWriter you can save and close it using
fw.close()
Writing this simple code into Java will result in unhandled error exceptions. Because the FileWriter constructor may throw exceptions (such as the file being write-protected) we need to ensure that our code handles these in the event of an error. This code will not compile if the constructor is not placed within a try-catch block as below:
public void WriteHelloWorld(String Filename)
{
try{
FileWriter fw = new FileWriter(Filename);
fw.write("My first written file!\n"); //\n signifies a new line
fw.write("Hello World!\n");
fw.close();
}
catch(IOException ex) //Did we generate an error?
{
System.out.println("Could not write to file"); //Explain what happened
System.exit(0); //Exit gracefully
}
}
FileOutputStream
[edit | edit source]File Input
[edit | edit source]Scanner
[edit | edit source]Scanner is a class that was made when it was decided by Sun that the java file IO API was too messy. Scanners make file IO significantly easier. To use Scanner, import the class from java.util:
import java.util.Scanner;
The scanner is a sort of wrapper class for a File, FileInputStream, or String class. The constructor of Scanner takes one of these objects as a parameter, like so:
Scanner ourScanner = new Scanner(new FileInputStream("ourfile.txt"));
Scanner ourScanner = new Scanner(new File("ourfile.txt"));
Scanner ourScanner = new Scanner("Even a String is a valid input");
Scanner includes a number of member methods that make reading Files easy. You can use a scanner to get the next item of a certain type from a stream with the methods next(), nextDouble(), nextFloat(), nextInt(), nextLine(), etc.... You can also determine if more of a certain type exist with the has*() methods and read and search for regular expressions.
Some example code:
FileInputStream istream = new FileInputStream(Filename);
Scanner ourScanner = new Scanner(istream);
while(ourScanner.hasNextDouble())
{
Double tmp = ourScanner.nextDouble();
System.out.println(tmp+"\n");
}
Using Strings and showing the use of extracting different data types
Scanner ourScanner = new Scanner("Rockefeller;John;43;180.5")
ourScanner.useDelimiter(";");
String lastName=ourScanner.next();
String firstName=ourScanner.next();
int age=ourScanner.nextInt();
double weight = ourScanner.nextDouble();
Delimiters
[edit | edit source]Scanner splits the elements of the File/String on Whitespace (spaces, tabs, endlines) by default. You can set the delimiter of the scanner using
ourScanner.useDelimiter(";");
Where we have chosen the semi-colon ";" as a delimiter.
Handling Errors and an Example Function
[edit | edit source]As with writing to files Java forces us to handle exceptions that can be produced if our Scanner is fed by a File or FileInputStream object. Note that this try-catch structure is not necessary if your scanner is only operating on a String. Sample code which handles this is below
//Count the number of lines present in a file.
//Inputs: Filename of chosen file
//Outputs: A count of the number of lines (int)
public int CountLines(String Filename)
{
int count = 0;
try
{
Scanner ourScanner = new Scanner(new File(Filename));
ourScanner.useDelimiter("\n");
while(ourScanner.hasNext())
{
ourScanner.next(); //Grab and forget the next line from the scanner
count++;
}
}
catch(FileNotFoundException ex)
{
System.out.println("File not Found");
System.exit(0);
}
return count;
}
Comma Separated Value Files
[edit | edit source]Because CSV is such a popular format it deserves special attention. In this case we want to separate the lines by endline-characters ('\n') and the entries within each line by commas (','). A common strategy is to use two scanners, one which reads lines from the file and another for each line which reads the individual entries.
References
[edit | edit source]- Scanner Java 8 documentation. Retrieved 23 January 2019.
- File Handling In Java
- How to create files in Java
- Read and write files in Java
- How to read and write files in Java 8