Ungajonga njani ukuba ngaba ifayile okanye isikhombisi sikhona kwiJava

KwiJava, zimbini iindlela eziphambili zokujonga ukuba ifayile okanye isikhombisi sikhona. Zezi:

1 - Files.exists ukusuka kwiphakheji yeNIO

2 - File.exists ukusuka kwiphakheji ye-IO yelifa


Makhe sibone eminye yemizekelo kwiphakeji nganye.



Jonga ukuba ikhona na ifayile (Java NIO)

Ikhowudi isebenzisa Path kunye Paths ukusuka kwiphakheji yeJava NIO ukujonga ukuba ikhona ifayile:


import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CheckFileExist {
public static void main(String[] args) {

Path path = Paths.get('/path/to/file/app.log');

if (Files.exists(path)) {

if (Files.isRegularFile(path)) {


System.out.println('App log file exists');

}

} else {

System.out.println('App log file does not exists');
}
} }


Jonga ukuba uLawulo lukhona na (Java NIO)

Ngokunjalo, ukuba sifuna ukukhangela ukuba isikhombisi sikhona kwiJava usebenzisa iphakheji ye-NIO:



import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CheckDirectoryExist {
public static void main(String[] args) {

Path path = Paths.get('/path/to/logs/');

if (Files.exists(path)) {

if (Files.isDirectory(path)) {


System.out.println('Logs directory exists');

}

} else {

System.out.println('Logs directory does not exist');
}
} }


Jonga ukuba ikhona na ifayile (iJava Ilifa IO)

Ukuba awusebenzisi iphakheji yeJava NIO, ungasebenzisa iphakheji ye-Java IO:

import java.io.File; public class CheckFileExists {
public static void main(String[] args) {

File file = new File('/path/to/file/app.log');

if(file.exists()) {

System.out.println('App log file exists');
} else {

System.out.println('App log file does not exist');
}
} }


Jonga ukuba uLawulo lukhona na (iJava yeLifa le-IO)

Ngokufanayo, ukujonga isikhombisi esinokusebenzisa:

import java.io.File; public class CheckFileExists {
public static void main(String[] args) {

File file = new File('/path/to/logs/');

if(file.isDirectory()) {

System.out.println('Logs directory exists');
} else {

System.out.println('Logs directory does not exist');
}
} }

Ukuqhubeka kokufunda












Uzifunda njani iifayile kwiJava enemizekelo

wdc.io










Ungazicima njani iifayile kunye nemikhombandlela kwiJava

wdc.io