string(175) "LC_CTYPE=C.UTF-8;LC_NUMERIC=en_US.utf8;LC_TIME=C;LC_COLLATE=C;LC_MONETARY=C;LC_MESSAGES=C;LC_PAPER=C;LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=C;LC_IDENTIFICATION=C" string(6) "PART4D" Objektorienteeritud programmeerimine (Narva Kolledž) - Kursused - Arvutiteaduse instituut
Arvutiteaduse instituut
  1. Kursused
  2. 2017/18 kevad
  3. Objektorienteeritud programmeerimine (Narva Kolledž) (P2NC.01.083)
EN
Logi sisse

Objektorienteeritud programmeerimine (Narva Kolledž) 2017/18 kevad

  • Home
  • Materials
  • Grading
  • Source Example
  • Links
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
  • Arvutiteaduse instituut
  • Loodus- ja täppisteaduste valdkond
  • Tartu Ülikool
Tehniliste probleemide või küsimuste korral kirjuta:

Kursuse sisu ja korralduslike küsimustega pöörduge kursuse korraldajate poole.
Õppematerjalide varalised autoriõigused kuuluvad Tartu Ülikoolile. Õppematerjalide kasutamine on lubatud autoriõiguse seaduses ettenähtud teose vaba kasutamise eesmärkidel ja tingimustel. Õppematerjalide kasutamisel on kasutaja kohustatud viitama õppematerjalide autorile.
Õppematerjalide kasutamine muudel eesmärkidel on lubatud ainult Tartu Ülikooli eelneval kirjalikul nõusolekul.
Courses’i keskkonna kasutustingimused