Dosya I/O
- Java kursu
- Orta seviye
- Ders 115/116
- 6 dk
Verileri JSON olarak kaydedip yüklersin.
Files.write ile dosyaya yazma
Siparişleri kalıcı yapmak için dosyaya yazmak gerekir. Java'nın java.nio.file.Files sınıfı bu işi kolaylaştırır. Files.write(Path.of("orders.txt"), lines) çağrısı bir List<String>'i dosyaya yazar; her eleman bir satır olur.
Geri okumak için Files.readAllLines(Path.of("orders.txt")) kullanılır; bu metot dosyadaki satırları bir List<String> olarak döndürür. İki metot da IOException fırlatabilir; bu yüzden main imzasına throws IOException eklenir.
IOException ve throws
Dosya işlemleri IOException fırlatabilir; bu işaretli (checked) bir istisnadır. Derleyici, ya try/catch ile ele alınmasını ya da metot imzasına throws IOException eklenmesini ister. Projede public static void main(String[] args) throws IOException yazmak en kısa yoldur.
Path.of("orders.txt") çağrısı göreli bir yol oluşturur; dosya çalışma dizininde oluşur. Files.write dosya yoksa oluşturur, varsa üzerine yazar. Files.readAllLines dosya yoksa NoSuchFileException fırlatır.
Uygulama save ve load metotlarını ekle
Üstteki OrderBook sınıfına save ve load metotlarını ekle. void save(String path) throws IOException metodu: orders.stream().map(o -> o.id + "|" + o.customer + "|" + o.amount).collect(Collectors.toList()) ile satırları üret ve Files.write(Path.of(path), lines) ile yaz. int load(String path) throws IOException metodu: return Files.readAllLines(Path.of(path)).size(); ile satır sayısını döndür. main imzasına throws IOException ekle. main içinde iki sipariş ekle, book.save("orders.txt"); çağr, System.out.println(book.load("orders.txt")); ile satır sayısını yazdır.
Başlangıç kodu
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
class Order {
String id;
String customer;
int amount;
Order(String id, String customer, int amount) {
this.id = id;
this.customer = customer;
this.amount = amount;
}
}
class OrderBook {
List<Order> orders = new ArrayList<>();
void add(Order o) { orders.add(o); }
void listAll() {
orders.forEach(o -> System.out.println(o.id + " " + o.customer + " " + o.amount));
}
List<Order> largeOrders() {
return orders.stream().filter(o -> o.amount >= 100).collect(Collectors.toList());
}
}
// OrderBook sınıfına save ve load metotlarını ekle (throws IOException)
// main: throws IOException ekle, iki sipariş ekle, save ve load çağır, sayıyı yazdırÖrnek çözüm
class Order {
String id;
String customer;
int amount;
Order(String id, String customer, int amount) {
this.id = id;
this.customer = customer;
this.amount = amount;
}
}
class OrderBook {
List<Order> orders = new ArrayList<>();
void add(Order o) { orders.add(o); }
void listAll() {
orders.forEach(o -> System.out.println(o.id + " " + o.customer + " " + o.amount));
}
List<Order> largeOrders() {
return orders.stream().filter(o -> o.amount >= 100).collect(Collectors.toList());
}
void save(String path) throws IOException {
List<String> lines = orders.stream()
.map(o -> o.id + "|" + o.customer + "|" + o.amount)
.collect(Collectors.toList());
Files.write(Path.of(path), lines);
}
int load(String path) throws IOException {
return Files.readAllLines(Path.of(path)).size();
}
}
public class Main {
public static void main(String[] args) throws IOException {
OrderBook book = new OrderBook();
book.add(new Order("1", "Ayşe", 50));
book.add(new Order("2", "Alex", 150));
book.save("orders.txt");
System.out.println(book.load("orders.txt"));
}
}Beklenen çıktı
2
Soru ve cevaplar
Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.
1 Files.write çağrısını tamamla
Files.____(Path.of("orders.txt"), lines);
Files.write(Path.of("orders.txt"), lines);
Açıklama: Files.write bir List<String>'i dosyaya yazar.
2 Dosya I/O kavramlarını eşleştir
| Kavram | Anlamı |
|---|---|
Files.write |
List<String> yazar |
Files.readAllLines |
List<String> okur |
Path.of |
Yol oluşturur |
throws IOException |
İstisnayı bildirir |
3 Files.readAllLines ne döndürür?
- List<String> Doğru cevap
- Bir int
- void
- Bir String
Açıklama: Files.readAllLines dosyadaki satırları List<String> olarak döndürür.