< Java

Java nio csomag

Szerző: Sallai András

Copyright © Sallai András, 2022

Licenc: CC Attribution-Share Alike 4.0 International

Web: https://szit.hu

Fájl olvasása

import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public class App { public static void readFile() { try { tryReadFile(); } catch (IOException e) { System.err.println("Hiba! A fájl nem olvasható!"); } } public static void tryReadFile() throws IOException { Path path = Paths.get("employees.txt"); Charset charset = StandardCharsets.UTF_8; List<String> lines = Files.readAllLines(path, charset); lines.forEach( line -> { String[] rows = line.split(":"); System.out.println(rows[0]); }); } public static void main(String[] args) throws Exception { readFile(); } }

Írás fájlba

import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class App { public static void writeFile() { try { tryWriteFile(); } catch (IOException e) { System.err.println("Hiba! A fájl nem olvasható!"); } } public static void tryWriteFile() throws IOException { Path path = Paths.get("adat.txt"); Charset cs = StandardCharsets.UTF_8; BufferedWriter writer = Files.newBufferedWriter(path, cs); writer.write("Valami"); writer.close(); } public static void main(String[] args) throws Exception { writeFile(); } }