Session 4 |
Files
In Java, there are several opportunities for communication with files. In this section, we will consider only one way how to get data from a file and write data into a file.
If you use IntelliJ, place your files into your project folder (next to src folder, not into src folder).
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 // we will study these two words in detail a bit 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 encoding // the keyword "try" attempts to open and close the file given as an argument try (PrintWriter pw = new PrintWriter(myFile, "UTF-8")) { // write into the file pw.print("Kerese "); pw.println("street"); } // create an instance of Scanner class to read from a file // the arguments are: the reference to the file and encoding try (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); } } } }
Useful link
We can apply various methods to instance myFile. Study the methods applicable to objects 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 |