जावा मध्ये, फाईल किंवा निर्देशिका अस्तित्त्वात आहेत का ते तपासण्यासाठी दोन प्राथमिक पद्धती आहेत. हे आहेतः
1 - Files.exists
| एनआयओ पॅकेज वरून
2 - File.exists
| लेगसी आयओ पॅकेज वरून
प्रत्येक पॅकेजमधील काही उदाहरणे पाहूया.
कोड वापरतो | _ _ + _ | आणि Path
फाइल अस्तित्त्वात आहे का ते तपासण्यासाठी जावा एनआयओ पॅकेज वरून:
Paths
|त्याचप्रमाणे एनआयओ पॅकेजद्वारे जावामध्ये निर्देशिका अस्तित्त्वात आहेत किंवा नाही हे आम्हाला तपासून पाहायचे असल्यासः
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');
}
} }
|आपण जावा एनआयओ पॅकेज वापरत नसल्यास, आपण जावा आयओ पॅकेजचा वारसा वापरू शकता:
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');
}
} }
|त्याचप्रमाणे डिरेक्टरी तपासण्यासाठी आपण वापरू शकतो.
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');
}
} }
|पुढील वाचन