Cách hiện thư mục bài làm trong java
Ngày đăng:
04/11/2022
Trả lời:
0
Lượt xem:
133
File directory_1 = new File("new"); // khai bao 1 folder ten la new trong project
directory_1.mkdir(); // lenh tao folder new tren o dia
Với lệnh thứ nhất chúng ta mới chỉ khai báo chứ chưa thể tạo, để tạo 1 folder ta phải viết thêm lệnh thứ hai.
Tạo thư mục trong đường dẫn bất kỳ: File directory_2 = new File(directory_1, "new1"); // tao thu muc new1 trong thu muc new vua tao directory_2.mkdir(); Tạo file trong project: File file = new File("test.txt"); // nam trong project try { file.createNewFile(); // tao file test.txt } catch (IOException e) { e.printStackTrace(); } Khi tạo file có thể xảy ra một số ngoại lệ nên chúng ta phải đặt lệnh file.createNewFile(); trong try catch. Code minh hoa: import java.io.File; import java.io.IOException; public class FileAndDirectory { public static void main(String[] args) { File directory_1 = new File("new"); // khai bao 1 folder ten la new trong project directory_1.mkdir(); // lenh tao folder new tren o dia File directory_2 = new File(directory_1, "new1"); // tao thu muc new1 trong thu muc new vua tao directory_2.mkdir(); //khai bao 3 file nam trong cac thu muc khac nhau File file_1 = new File("test.txt"); // nam trong project File file_2 = new File(directory_1,"test1.txt"); // nam trong directory_2 (new1) File file_3 = new File("/media/quan/DATA/Dropbox/STUDY/PROGRAM/Java/code/JavaBasic/new/new1","test2.txt"); // new la directory1, new1 la directory2 try { file_1.createNewFile(); // tao file test.txt file_2.createNewFile(); // tao file test1.txt file_3.createNewFile(); // tao file test2.txt } catch (IOException e) { e.printStackTrace(); } } } Do mình dùng ubuntu nên đường dẫ là /media/quan/DATA/…. Nếu bạn dùng windows đường dẫn có thể là C:foldertext.txt
Đăng nhập tài khoảnĐăng ký tài khoản mớiChưa có tài khoản ?Đã có tài khoản ? |