Java File Class - Javatpoint
Java File Class - Javatpoint
ADVERTISEMENT
The File class is an abstract representation of file and directory pathname. A pathname can be either
absolute or relative.
The File class have several methods for working with directories and files such as creating new
directories or files, deleting and renaming directories or files, listing the contents of a directory etc.
Fields
ADVERTISEMENT
Constructor Description
File(File parent, String It creates a new File instance from a parent abstract pathname and a
child) child pathname string.
File(String pathname) It creates a new File instance by converting the given pathname string
into an abstract pathname.
File(String parent, String It creates a new File instance from a parent pathname string and a
child) child pathname string.
File(URI uri) It creates a new File instance by converting the given file: URI into an
abstract pathname.
Useful Methods
ADVERTISEMENT
boolean canWrite() It tests whether the application can modify the file
denoted by this abstract pathname.String[]
boolean canExecute() It tests whether the application can execute the file
denoted by this abstract pathname.
boolean canRead() It tests whether the application can read the file
denoted by this abstract pathname.
String[] list(FilenameFilter filter) It returns an array of strings naming the files and
directories in the directory denoted by this abstract
pathname that satisfy the specified filter.
boolean mkdir() It creates the directory named by this abstract
pathname.
import java.io.*;
public class FileDemo {
public static void main(String[] args) {
try {
File file = new File("javaFile123.txt");
if (file.createNewFile()) {
System.out.println("New File is created!");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
import java.io.*;
public class FileDemo2 {
public static void main(String[] args) {
Output:
testFile1.txt
/home/Work/Project/File/testFile1.txt
true
/home/Work/Project/File/testFile1.txt Exists? true
import java.io.*;
public class FileExample {
public static void main(String[] args) {
File f=new File("/Users/sonoojaiswal/Documents");
String filenames[]=f.list();
for(String filename:filenames){
System.out.println(filename);
}
}
}
Output:
"info.properties"
"info.properties".rtf
.DS_Store
.localized
Alok news
apache-tomcat-9.0.0.M19
apache-tomcat-9.0.0.M19.tar
bestreturn_org.rtf
BIODATA.pages
BIODATA.pdf
BIODATA.png
struts2jars.zip
workspace
import java.io.*;
public class FileExample {
public static void main(String[] args) {
File dir=new File("/Users/sonoojaiswal/Documents");
File files[]=dir.listFiles();
for(File file:files){
System.out.println(file.getName()+" Can Write: "+file.canWrite()+"
Is Hidden: "+file.isHidden()+" Length: "+file.length()+" bytes");
}
}
}
Output:
← Prev Next →
Feedback