![]() | 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.
import java.io.File; // import package that handles Files
import java.io.PrintWriter; // import package that can write into a file
import java.util.Scanner; // import package that can read from a file
public class ReadWriteFile {
// add two words into the header of main method to handle errors (will study in detail later)
public static void main(String[] args) throws Exception {
// create an instance of File class and define the file to create connection with
File myFile = new File("c:/temp/mydata.txt");
// 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.");
// to write into a file, create an instance of PrintWriter class
// the arguments are: the reference to the file and encording
PrintWriter pw = new PrintWriter(myFile, "UTF-8");
// write into the file
pw.print("Kerese ");
pw.println("street");
// close the connection witht he file
pw.close();
// to read from a file, create an instance of Scanner class and
// the arguments are: the reference to the file and encording
Scanner sc = new Scanner(myFile, "UTF-8");
// read data from the file using a loop
while (sc.hasNextLine()) { // method hasNextLine returns a boolean value
// if the Scanner has another line in its input to read
String line = sc.nextLine(); // method nextLine returns the line that was read
System.out.println(line);
}
// close the connection with the file
sc.close();
}
}
Useful link: We can apply various methods to instance myFile. Study the methods applicable to the instances of File class here.
Useful link: The full list of PrintWriter class fields, constructors, methods and their description can be found here.
Useful link: Read about different encodings here.
![]() | Session 4 | ![]() |

