Files
G4G0-1/Semester 2/Programming 2/Week 1/Week 1 Programming 2.md

61 lines
1.8 KiB
Markdown

# Files and Java.io
### Files
```java
import java.utils.*
import java.io.*
public void writeAnimalData( String fileName ) throws FileNotFoundException
{
PrintWriter pWriter = new PrintWriter( fileName );
for( Animal a: animalCollection )
{
String lineOfOutput = a.getName() + "" + a.getSpecies();
pWriter.println( lineOfOutput );
}
pWriter.close();
}
```
Without using `throws FileNotFoundException`, a compilation error will occur. Any method that may possibly throw an exception must advertise this by using `throws` to discard the error to avoid a crash.
The method `PrintWriter` itself, also includes the clause, as can be seen in the Java.io documentation.
```java
public Zoo( String fileName ) throws FileNotFoundException
{
this();
readAnimalData( fileName );
}
```
This allows us to use the code from the default constructor without duplicating the code. `this();` must be the first keyword in the method.
### Scanner
The scanner class is used to read data from the keyboard / file.
Once a Scanner object has been created (from Java.util), data can be read: `new Scanner( System.in );`
A Scanner object breaks the input into tokens separated by whitespaces. Each line of data in the file can be easily read with the following:
```java
String name = scanner.next();
String species = scanner.next();
```
#### Ex
```java
public void readAnimalData( String fileName) throws FileNotFoundException
{
File dataFile = new File( fileName ); //Create file to write to.
Scanner scanner = new Scanner( dataFile ); //Initialise scanner.
while( scanner.hasNext() )
{
String name = scanner.next(); //First token in line.
String species = scanner.next(); //Second token in line.
StoreAnimal( new Animal( species, name ) ); //Store the tokens as an animal in list.
scanner.nextLine(); //Increment to next line.
}
scanner.close();
}
```