If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
File handling , किसी भी application के लिए important होता है , Java में file handle करने के लिए कई सारे methods define किये गए हैं जिनकी help से आप easily files को create / update या delete कर सकते हैं।
Java में file handle करने के लिए java.io package की File class का use किया जाता है। File class वो सभी useful methods provide कराती है जिनकी help से आप easily files को need के according handle कर सकते हैं।
// import File class from java.io package. import java.io.File; File myObj = new File("myfile.txt");
file handling में use किये जाने वाले कुछ methods की list नीचे दी गयी है -
Method | Return Type | Description |
---|---|---|
canRead() | Boolean | Tests whether the file is readable or not. |
canWrite() | Boolean | Tests whether the file is writable or not. |
createNewFile() | Boolean | Creates an empty file. |
delete() | Boolean | Deletes a file. |
exists() | Boolean | Tests whether the file exists. |
getName() | String | Returns the name of the file |
getAbsolutePath() | String | Returns the absolute path name of the file. |
length() | Long | Returns the size of the file in bytes. |
list() | String[] | Returns an array of the files in the directory. |
mkdir() | Boolean | Creates a directory. |
File : FileTest.java
import java.io.File;
public class FileTest {
public static void main(String[] args) {
String filename = "demo.txt";
File fObj = new File(filename);
// check if file exists.
if(fObj.exists()) {
System.out.println(filename + " file exists.");
} else {
System.out.println(filename + " file does not exists.");
}
// check if file is readable readable.
if(fObj.canRead()) {
System.out.println(filename + " file is not readable.");
} else {
System.out.println(filename + " file is not readable.");
}
// delete file.
if(fObj.delete()) {
System.out.println(filename + " file deleted successfully.");
} else {
System.out.println(filename + " file could not delete.");
}
}
}
demo.txt file does not exists. demo.txt file is not readable. demo.txt file could not delete.
ऊपर दिए गए Example में , कुछ basic methods का use किया गया है , बाकी file को create , read write करना आप next topics में पढ़ेंगे।