[[oktatas:programozás:java|< Java]]
====== Java nio csomag ======
* **Szerző:** Sallai András
* Copyright (c) 2022, Sallai András
* Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC BY-SA 4.0]]
* 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 cs = StandardCharsets.UTF_8;
List lines = Files.readAllLines(path, cs);
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();
}
}