Xóa file trong Java
Miêu tả vấn đề
Cách xóa một file trong Java?
Giải pháp
Ví dụ sau minh họa cách xóa một file bởi sử dụng phương thức delete() của lớp File trong Java.
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
BufferedWriter out = new BufferedWriter
(new FileWriter("filename"));
out.write("aString1\n");
out.close();
boolean success = (new File
("filename")).delete();
if (success) {
System.out.println("The file has
been successfully deleted");
}
BufferedReader in = new BufferedReader
(new FileReader("filename"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
}
catch (IOException e) {
System.out.println("exception occoured"+ e);
System.out.println("File does not exist
or you are trying to read a file that
has been deleted");
}
}
}
}
Kết quả
Code trên sẽ cho kết quả sau:
The file has been successfully deleted exception occouredjava.io.FileNotFoundException: filename (The system cannot find the file specified) File does not exist or you are trying to read a file that has been deleted
Công cụ giáo viên (2048.VN)
Tạo- trộn đề thi miễn phí từ file PDF, Word, Giao bài nhanh chóng, Hoàn toàn Free
Các bạn có thể mua thêm khóa học JAVA CORE ONLINE VÀ ỨNG DỤNG cực hay, giúp các bạn vượt qua các dự án trên trường và đi thực tập Java. Khóa học có giá chỉ 300K, nhằm ưu đãi, tạo điều kiện cho sinh viên cho thể mua khóa học.
Nội dung khóa học gồm 16 chuơng và 100 video cực hay, học trực tiếp tại https://www.udemy.com/tu-tin-di-lam-voi-kien-thuc-ve-java-core-toan-tap/ Bạn nào có nhu cầu mua, inbox trực tiếp a Tuyền, cựu sinh viên Bách Khoa K53, fb: https://www.facebook.com/tuyen.vietjack
Follow facebook cá nhân Nguyễn Thanh Tuyền https://www.facebook.com/tuyen.vietjack để tiếp tục theo dõi các loạt bài mới nhất về Java,C,C++,Javascript,HTML,Python,Database,Mobile.... mới nhất của chúng tôi.
Bài học Bài tập Java phổ biến tại vietjack.com:

