- IOException - Nếu có lỗi xảy ra trong quá trình tạo file.
- SecurityException - Nếu tồn tại Security manager và phương thức SecurityManager.checkWrite(java.lang.String) không có quyền write vào file.
Chương trình cài đặt:
Chương trình sau sẽ tạo ra một file txt có tên là "newfile.txt" trong ổ C. Để tạo file ở một ổ đĩa bất kỳ chỉ cần thay thổi đường dẫn tạo file.
package simplecodecjava.blogspot.com;
import java.io.File;
import java.io.IOException;
public class CreateFileDemo {
public static void main(String[] args) {
try {
File file = new File("C:\\newfile.txt");
/*
* Nếu trong ổ C chưa tồn tại file newfile.txt thì phương thức createNewFile() trả về true
* Nếu file đã tồn tại thì phương thức createNewFile() trả về false.
*/
boolean fvar = file.createNewFile();
if (fvar) {
System.out.println("File đã được tạo thành công");
} else {
System.out.println("File đã tồn tại");
}
} catch (IOException e) {
System.out.println("Đã xảy ra lỗi:");
e.printStackTrace();
}
}
}

0 Comment to "[Java] Tạo file trong Java"
Post a Comment