![]() | Session 4 | ![]() |
Files
In Java, there are several opportunities for communicate with files. In this section, we will get to know only one way how to get data from a file and write data into a file.
First of all, create an instance of File class and define the file with which we want to create a connection:
java.io.File myFile = new java.io.File("c:/temp/mydata.txt");
If typing the package of the class becomes too annoying, the package can be mentioned on the very top of the program and the class can be addressed without its package name:
// import package with the class
import java.io.File;
// use only class name
File myFile = new File("c:/temp/mydata.txt");
Useful link: We can apply various methods to instance myFile. Study the methods applicable to the instances of File class here.
Example:
// check if the file already exists
if (myfile.exists())
System.out.println("This file already exists in this folder.");
else
System.out.println("This file does not exist in this folder.");
If we want to write something into the file, at first, we need to create an instance of PrintWriter class.
Useful link: The full list of PrintWriter class fields, constructors, methods and their description can be found here.
If we use the constructor whose parameter is a File object
java.io.PrintWriter pw = new java.io.PrintWriter(MyFile, "UTF-8");
we will get an error (unhandled exception). We will study the exceptions a bit later, but right now add two words into the header of main method:
public static void main(String[] args) throws Exception
Next, we can write into the file using the methods of PrintWriter class such as print and println:
pw.print("Kerese ");
pw.println("street");
pw.print("Pushkini ");
pw.println("steet");
pw.print("Kreenholm ");
pw.println("street");
// when communication with the file is over, close the file
pw.close();
Useful link: Read about different encodings here.
If we want to read the data from a file, we can use Scanner class (the same class that we used for reading data from the keyboard). When we create an instance of Scanner class, we have to give the reference to the file as an argument:
java.util.Scanner sc = new java.util.Scanner(myFile, "UTF-8");
Using methods hasNextLine (returns a boolean value if the scanner has another token in its input or not) and nextLine (returns the input that was skipped), we can read the data from the file and print on the screen:
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line);
}
sc.close();
![]() | Session 4 | ![]() |

