1. Tạo tập tin mới 2. Ghi dữ liệu vào tập tin từ bàn phím 3. In ra đường dẫn của tập tin đã tạo 4. Đọc dữ liệu từ tập tin
import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Scanner;
public class FileReadWriteExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
// Tạo tập tin mới
File file = new File("input.txt");
if (!file.exists()) {
file.createNewFile();
}
// Ghi dữ liệu vào tập tin từ bàn phím
FileWriter writer = new FileWriter(file);
System.out.println("Nhập dữ liệu để ghi vào tập tin (Nhấn Enter để kết thúc): ");
String input;
while (!(input = scanner.nextLine()).isEmpty()) {
writer.write(input + "\n");
}
writer.close();
System.out.println("Ghi dữ liệu vào tập tin thành công.");
// In ra đường dẫn của tập tin đã tạo
System.out.println("Đường dẫn của tập tin: " + file.getAbsolutePath());
// Đọc dữ liệu từ tập tin
System.out.println("Đọc dữ liệu từ tập tin:");
FileReader reader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
System.out.println("Đọc dữ liệu từ tập tin thành công.");
} catch (IOException e) {
System.out.println("Đã xảy ra lỗi: " + e.getMessage());
} finally {
scanner.close();
}
}
}
Không có nhận xét nào:
Đăng nhận xét