I-Java Yakha Izibonelo Zefayela

Ukwakha amafayela kuJava kulula. Kulokhu okuthunyelwe, sizobheka izindlela ezine ezihlukile zokwenza amafayela kuJava. Konke okudingeka sikwenze ukungenisa iphakethe elifanele futhi sisebenzise izindlela ezifanele.

Izibonelo ezingezansi zisebenzisa i- java.io.file, java.io.fileOutputStream, ne- java.nio iphakethe. Lezi zigaba zinikezwa ngaphandle kwebhokisi ku-Java API. Futhi sibheka ukudala ifayili nge-Apache Commons.

Dala Ifayela ngesigaba se-java.io.file

Esibonelweni sokuqala, sizosebenzisa i- _ _ + _ | indlela evela createNewFile() isigaba. Le ndlela ibuyisa inani le-boolean. Ibuyisa amanga uma ngabe ifayili selivele likhona, noma liyiqiniso uma lenziwe.

java.io.file

QAPHELA: Isibonelo esingenhla sakha ifayela elingenalutho endaweni enikeziwe.

Okuhlobene:

Isebenzisa Java.io.fileOutputStream

Isibonelo esilandelayo sisebenzisa import java.io.File; import java.io.IOException; public class CreateFileJavaExamples {
public static void main(String[] args) {
File file = new File('c://examples//newFile.txt');

try {

if (file.createNewFile()) {


System.out.println('File create');

} else {


System.out.println('File already exists!');

}
} catch (IOException e) {

System.out.println(e.getMessage());
}
} }
. Kubalulekile ukuthi wazi ukuthi lokhu kusetshenziselwa kakhulu ukudala ifayili bese ubhala okuqukethwe kulo ngasikhathi sinye.



fileOutputStream

Uma ifayela lingekho, indlela engenhla izolakha. Uma ifayili likhona, liyadlula import java.io.FileOutputStream; public class CreateFileJavaExamples {
public static void main(String[] args) {
try {

new FileOutputStream('newFile.txt', true);
} catch (Exception e) {

System.out.println(e.getMessage());
}
} }
kuzovele kufakwe okuqukethwe kuyo.

QAPHELA: Qaphela lapho usebenzisa true. Uma ifayili likhona nokuqukethwe, uma sidlula fileOutputStream njengepharamitha ku- false indlela, izobhala ngaphezulu ifayela bese okuqukethwe kuzolahleka!

Dala Ifayela ngeJava.nio Package

Esibonelweni esilandelayo, sizosebenzisa fileOutputStream package eyethulwe ku-JDK 7.

Ukuze wakhe ifayela nge- java.nio package, okokuqala sidinga ukusetha indlela bese sisebenzisa i- nio indlela kusuka createFile() isigaba. Ukwakha amafayela nge- | | + _ | | package inketho ekhethwayo njengoba i-API inembile kakhulu.

Files

Isibonelo esingenhla sekhodi sithatha indlela nio isivele ikhona.

Ama-Apache Commons FileUtils

Uma ungafuni ukusebenzisa imitapo yolwazi ejwayelekile enikezwe ngaphandle kwebhokisi kusuka kuJava, ungasebenzisa import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CreateFileJavaExamples {
public static void main(String[] args) {
try {

Path newFilePath = Paths.get('src/test/resources/newFile.txt');

Files.createFile(newFilePath);
}
catch (IOException e) {

}
} }
isigaba kusuka Ama-Apache Commons

src/test/resources

Esibonelweni esingenhla, sisebenzisa i- FileUtils indlela yokwakha ifayela.