[Java] Creat file, directory in Java

Tạo thư mục trong project :

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.
Tạo file trong thư mục bất kỳ tương tự như tạo thư mục, chúng ta chỉ cần thêm đường dẫn trong khi khai báo file.

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
Để lấy đường dẫn của thư mục bạn có thể xem bài hướng dẫn sau:
Lấy đường dẫn file trong Java – Get File Path in Java
Đường dẫn thư mục trong Ubuntu – The path folder in Ubuntu
Với windows: clickphải chuột chọn properties đường link ở mục location