Java:Failist lugemine
Java sisend-väljund näib liiga keeruline. Üks hea omadus, mis selle keerulisusega saavutatakse, on see, et nii klaviatuurilt kui ka failist saab andmeid lugeda samade kõrgema kihi objektidega nagu BufferedReader
või Scanner
. Allpool on paar näidet, kuidas faili võib lugeda. Lisaks kahele mainitud andmetöötlus objekti on failide lugemiseks veel täiendav võimalus Files.readAllLines()
.
Iga konkreetne andmetöötlus objekt tahab saada argumendiks Path
tüüpi objekti. Path
konstrueeritakse kasutades faili asukohta kõvakettal. Allpool on koodinäide, kuidas luua erinevad andmetöötlusobjektid.
Koodinäide:
<source lang="java"> import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Scanner;
public class ReadFile {
/** * Filename to be read. */ public static final String FILENAME = "test.txt";
public static void main(String[] args) { // Files.readAllLines (Java 1.7+) try { for (String line : readSmallFile(FILENAME)) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } // BufferedReader try { System.out.println(readFileBuffered(FILENAME)); } catch (IOException e) { e.printStackTrace(); }
// Scanner try { System.out.println(readFileScanner(FILENAME)); } catch (IOException e) { e.printStackTrace(); }
// read only numbers using Scanner try { for (int number : readOnlyNumbers(FILENAME)) { System.out.println(number); } } catch (IOException e) { e.printStackTrace(); } }
/** * Reads (a small) file and returns list of lines (strings). * @param filename Filename to be read. * @return List of lines. * @throws IOException */ public static List<String> readSmallFile(String filename) throws IOException { Path path = Paths.get(filename); List<String> lines = Files.readAllLines(path); return lines; }
/** * Reads file using Scanner. * @param filename filename to be read. * @return The contents of the file as one string. * @throws IOException */ public static String readFileScanner(String filename) throws IOException { String ret = ""; Path path = Paths.get(filename); Scanner scanner = new Scanner(path); while (scanner.hasNextLine()) { // "\n" -> newline ret += scanner.nextLine() + "\n"; } scanner.close(); return ret; } /** * Read file using BufferedReader. * @param filename Filename to be read. * @return The contents of the file as one string. * @throws IOException */ public static String readFileBuffered(String filename) throws IOException { String ret = ""; Path path = Paths.get(filename); BufferedReader reader = Files.newBufferedReader(path); String line; while ((line = reader.readLine()) != null) { ret += line + "\n"; } reader.close(); return ret; }
/** * Reads only numbers from the input file. Everything else is ignored. * @param filename Filename to be read. * @return A list of numbers from the file. * @throws IOException */ public static List<Integer> readOnlyNumbers(String filename) throws IOException { List<Integer> numbers = new ArrayList<Integer>(); Path path = Paths.get(filename); Scanner scanner = new Scanner(path); while (scanner.hasNext()) { if (scanner.hasNextInt()) { numbers.add(scanner.nextInt()); } else { // we have to read the token scanner.next(); } } return numbers; }
} </source>
Kui arendate Eclipse'is, siis vaikimisi loetakse faili projekti juurkaustast. Seega minul on fail "test.txt" kohe projekti all. Sisu on järgmine:
1 2 3 4 tere 5 tere 6
Koodis on näide, kuidas lugeda failist ainult numbreid. Ehk siis juba tuttav Scanner
objekt kasutatav ka failide puhul.