Difference between revisions of "JAVA: File Class"

From OnnoWiki
Jump to navigation Jump to search
(Created page with "The File class is Java’s representation of a file or directory pathname. Because file and directory names have different formats on different platforms, a simple string is n...")
 
 
(7 intermediate revisions by the same user not shown)
Line 1: Line 1:
The File class is Java’s representation of a file or directory pathname. Because file and directory names have different formats on different platforms, a simple string is not adequate to name them. The File class contains several methods for working with the pathname, deleting and renaming files, creating new directories, listing the contents of a directory, and determining several common attributes of files and directories.  
+
Class File adalah representasi Java dari pathname file atau direktori. Karena nama file dan direktori memiliki format yang berbeda pada platform yang berbeda, string sederhana tidak cukup untuk menamainya. Class File berisi beberapa method untuk bekerja dengan pathname, menghapus dan mengganti nama file, membuat direktori baru, membuat daftar isi direktori, dan menentukan beberapa atribut umum dari file dan direktori.
  
It is an abstract representation of files and directory pathnames.
+
* Ini adalah representasi abstrak dari file dan pathname direktori.
A pathname, whether abstract or in string form can be either absolute or relative. The parent of an abstract pathname may be obtained by invoking the getParent() method of this class.
+
* pathname, apakah abstrak atau dalam bentuk string dapat berupa absolut atau relatif. Induk dari pathname abstrak dapat diperoleh dengan memanggil metode getParent() dari Class ini.
First of all, we should create the File class object by passing the filename or directory name to it. A file system may implement restrictions to certain operations on the actual file-system object, such as reading, writing, and executing. These restrictions are collectively known as access permissions.
+
* Pertama-tama, kita harus membuat object Class File dengan meneruskan nama file atau nama direktori ke sana. Sistem file dapat menerapkan pembatasan operasi tertentu pada objek sistem file yang sebenarnya, seperti membaca, menulis, dan mengeksekusi. Pembatasan ini secara kolektif dikenal sebagai izin akses.
Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.
+
* Contoh Class File tidak dapat diubah; yaitu, setelah dibuat, pathname abstrak yang diwakili oleh object File tidak akan pernah berubah.
How to create a File Object?
 
  
A File object is created by passing in a string that represents the name of a file, a String, or another File object. For example,
 
  
File a = new File("/usr/local/bin/geeks");
 
This defines an abstract file name for the geeks file in the directory /usr/local/bin. This is an absolute abstract file name.
 
  
Constructors of File Class
+
==Bagaimana cara membuat Object File?==
File(File parent, String child): Creates a new File instance from a parent abstract pathname and a child pathname string.
+
 
File(String pathname): Creates a new File instance by converting the given pathname string into an abstract pathname.
+
Object File dibuat dengan meneruskan string yang mewakili nama file, String, atau objek File lainnya. Sebagai contoh,
File(String parent, String child): Creates a new File instance from a parent pathname string and a child pathname string.
+
 
File(URI uri): Creates a new File instance by converting the given file: URI into an abstract pathname.
+
File a = new File("/usr/local/bin/geeks");
Methods of File Class
+
 
S. No. Method Description Return Type
+
Ini mendefinisikan nama file abstrak untuk file Geeks di direktori /usr/local/bin. Ini adalah nama file abstrak yang bersifat absolut.
1. canExecute() Tests whether the application can execute the file denoted by this abstract pathname. boolean
+
 
2. canRead() Tests whether the application can read the file denoted by this abstract pathname. boolean
+
 
3. canWrite() Tests whether the application can modify the file denoted by this abstract pathname. boolean
+
==Constructors of File Class==
4. compareTo(File pathname) Compares two abstract pathnames lexicographically. int
+
 
5. createNewFile() Atomically creates a new, empty file named by this abstract pathname. boolean
+
* File(File parent, String child): Buat instance new file dari parent abstract pathname dan child pathname string.
6. createTempFile(String prefix, String suffix) Creates an empty file in the default temporary-file directory. File
+
* File(String pathname): Buat instance new File dengan cara mengubah pathname string yang diberikan menjadi abstract pathname.
7. delete() Deletes the file or directory denoted by this abstract pathname. boolean
+
* File(String parent, String child): Buat instance new File dari parent pathname string dan child pathname string.
8. equals(Object obj) Tests this abstract pathname for equality with the given object. boolean
+
* File(URI uri): Buat instance new File dengan cara mengubah file: URI yang diberikan menjadi abstract pathname.
9. exists() Tests whether the file or directory denoted by this abstract pathname exists. boolean
+
 
10. getAbsolutePath() Returns the absolute pathname string of this abstract pathname. String
+
==Method dari File Class==
11. list() Returns an array of strings naming the files and directories in the directory. String[]
+
 
12. getFreeSpace() Returns the number of unallocated bytes in the partition. long
+
No. Method Description Return Type
13. getName() Returns the name of the file or directory denoted by this abstract pathname. String
+
1. canExecute() Tests whether the application can execute the file denoted by this abstract pathname. boolean
14. getParent() Returns the pathname string of this abstract pathname’s parent. String
+
2. canRead() Tests whether the application can read the file denoted by this abstract pathname. boolean
15. getParentFile() Returns the abstract pathname of this abstract pathname’s parent. File
+
3. canWrite() Tests whether the application can modify the file denoted by this abstract pathname. boolean
16. getPath() Converts this abstract pathname into a pathname string. String
+
4. compareTo(File pathname) Compares two abstract pathnames lexicographically. int
17. setReadOnly() Marks the file or directory named so that only read operations are allowed. boolean
+
5. createNewFile() Atomically creates a new, empty file named by this abstract pathname. boolean
18. isDirectory() Tests whether the file denoted by this pathname is a directory. boolean
+
6. createTempFile(String prefix, String suffix) Creates an empty file in the default temporary-file directory. File
19. isFile() Tests whether the file denoted by this abstract pathname is a normal file. boolean
+
7. delete() Deletes the file or directory denoted by this abstract pathname. boolean
20. isHidden() Tests whether the file named by this abstract pathname is a hidden file. boolean
+
8. equals(Object obj) Tests this abstract pathname for equality with the given object. boolean
21. length() Returns the length of the file denoted by this abstract pathname. long
+
9. exists() Tests whether the file or directory denoted by this abstract pathname exists. boolean
22. listFiles() Returns an array of abstract pathnames denoting the files in the directory. File[]
+
10. getAbsolutePath() Returns the absolute pathname string of this abstract pathname. String
23. mkdir() Creates the directory named by this abstract pathname. boolean
+
11. list() Returns an array of strings naming the files and directories in the directory. String[]
24. renameTo(File dest) Renames the file denoted by this abstract pathname. boolean
+
12. getFreeSpace() Returns the number of unallocated bytes in the partition. long
25. setExecutable(boolean executable) A convenience method to set the owner’s execute permission. boolean
+
13. getName() Returns the name of the file or directory denoted by this abstract pathname. String
26. setReadable(boolean readable) A convenience method to set the owner’s read permission. boolean
+
14. getParent() Returns the pathname string of this abstract pathname’s parent. String
27. setReadable(boolean readable, boolean ownerOnly) Sets the owner’s or everybody’s read permission. boolean
+
15. getParentFile() Returns the abstract pathname of this abstract pathname’s parent. File
28. setWritable(boolean writable) A convenience method to set the owner’s write permission. boolean
+
16. getPath() Converts this abstract pathname into a pathname string. String
29. toString() Returns the pathname string of this abstract pathname. String
+
17. setReadOnly() Marks the file or directory named so that only read operations are allowed. boolean
30. toURI() Constructs a file URI that represents this abstract pathname. URI
+
18. isDirectory() Tests whether the file denoted by this pathname is a directory. boolean
Example 1: Program to check if a file or directory physically exists or not.
+
19. isFile() Tests whether the file denoted by this abstract pathname is a normal file. boolean
 +
20. isHidden() Tests whether the file named by this abstract pathname is a hidden file. boolean
 +
21. length() Returns the length of the file denoted by this abstract pathname. long
 +
22. listFiles() Returns an array of abstract pathnames denoting the files in the directory. File[]
 +
23. mkdir() Creates the directory named by this abstract pathname. boolean
 +
24. renameTo(File dest) Renames the file denoted by this abstract pathname. boolean
 +
25. setExecutable(boolean executable) A convenience method to set the owner’s execute permission. boolean
 +
26. setReadable(boolean readable) A convenience method to set the owner’s read permission. boolean
 +
27. setReadable(boolean readable, boolean ownerOnly) Sets the owner’s or everybody’s read permission.boolean
 +
28. setWritable(boolean writable) A convenience method to set the owner’s write permission. boolean
 +
29. toString() Returns the pathname string of this abstract pathname. String
 +
30. toURI() Constructs a file URI that represents this abstract pathname. URI
 +
 
 +
==Example 1: Program to check if a file or directory physically exists or not.==
 +
 
 +
// In this Java program, we accepts a file or directory name from
 +
// command line arguments. Then the program will check if
 +
// that file or directory physically exist or not and
 +
// it displays the property of that file or directory.
 +
 
 +
import java.io.File;
 +
 
 +
// Displaying file property
 +
class fileProperty {
 +
    public static void main(String[] args)
 +
    {
 +
 
 +
        // accept file name or directory name through
 +
        // command line args
 +
        String fname = args[0];
 +
 
 +
        // pass the filename or directory name to File
 +
        // object
 +
        File f = new File(fname);
 +
 
 +
        // apply File class methods on File object
 +
        System.out.println("File name :" + f.getName());
 +
        System.out.println("Path: " + f.getPath());
 +
        System.out.println("Absolute path:"
 +
                            + f.getAbsolutePath());
 +
        System.out.println("Parent:" + f.getParent());
 +
        System.out.println("Exists :" + f.exists());
 +
 
 +
        if (f.exists()) {
 +
            System.out.println("Is writable:"
 +
                                + f.canWrite());
 +
            System.out.println("Is readable" + f.canRead());
 +
            System.out.println("Is a directory:"
 +
                                + f.isDirectory());
 +
            System.out.println("File Size in bytes "
 +
                                + f.length());
 +
        }
 +
    }
 +
}
  
// In this Java program, we accepts a file or directory name from
 
// command line arguments. Then the program will check if
 
// that file or directory physically exist or not and
 
// it displays the property of that file or directory.
 
 
 
import java.io.File;
 
 
 
// Displaying file property
 
class fileProperty {
 
    public static void main(String[] args)
 
    {
 
 
 
        // accept file name or directory name through
 
        // command line args
 
        String fname = args[0];
 
 
 
        // pass the filename or directory name to File
 
        // object
 
        File f = new File(fname);
 
 
 
        // apply File class methods on File object
 
        System.out.println("File name :" + f.getName());
 
        System.out.println("Path: " + f.getPath());
 
        System.out.println("Absolute path:"
 
                          + f.getAbsolutePath());
 
        System.out.println("Parent:" + f.getParent());
 
        System.out.println("Exists :" + f.exists());
 
 
 
        if (f.exists()) {
 
            System.out.println("Is writable:"
 
                              + f.canWrite());
 
            System.out.println("Is readable" + f.canRead());
 
            System.out.println("Is a directory:"
 
                              + f.isDirectory());
 
            System.out.println("File Size in bytes "
 
                              + f.length());
 
        }
 
    }
 
}
 
 
Output:
 
Output:
 +
File name :file.txt
 +
Path: file.txt
 +
Absolute path:C:\Users\akki\IdeaProjects\codewriting\src\file.txt
 +
Parent:null
 +
Exists :true
 +
Is writable:true
 +
Is readabletrue
 +
Is a directory:false
 +
File Size in bytes 20
  
File name :file.txt
+
==Example 2: Program to display all the contents of a directory==
Path: file.txt
 
Absolute path:C:\Users\akki\IdeaProjects\codewriting\src\file.txt
 
Parent:null
 
Exists :true
 
Is writable:true
 
Is readabletrue
 
Is a directory:false
 
File Size in bytes 20
 
Example 2: Program to display all the contents of a directory
 
  
Here we will accept a directory name from the keyboard and then display all the contents of the directory. For this purpose, list() method can be used as:  
+
Di sini kita akan menerima nama direktori dari keyboard dan kemudian menampilkan semua isi direktori. Untuk tujuan ini, method list() dapat digunakan sebagai berikut:
  
String arr[]=f.list();
 
In the preceding statement, the list() method causes all the directory entries copied into the array arr[]. Then pass these array elements arr[i] to the File object and test them to know if they represent a file or directory.
 
  
// Java Program to display all  
+
String arr[]=f.list();
// the contents of a directory
+
 
import java.io.BufferedReader;
+
Dalam pernyataan sebelumnya, metode list() menyebabkan semua entri direktori disalin ke dalam array arr[]. Kemudian berikan elemen array ini arr[i] ke objek File dan uji untuk mengetahui apakah elemen tersebut mewakili file atau direktori.
import java.io.File;
+
 
import java.io.IOException;
+
// Java Program to display all  
import java.io.InputStreamReader;
+
// the contents of a directory
 
+
import java.io.BufferedReader;
// Displaying the contents of a directory
+
import java.io.File;
class Contents {
+
import java.io.IOException;
    public static void main(String[] args)
+
import java.io.InputStreamReader;
        throws IOException
+
 
    {
+
// Displaying the contents of a directory
        // enter the path and dirname from keyboard
+
class Contents {
        BufferedReader br = new BufferedReader(
+
    public static void main(String[] args)
            new InputStreamReader(System.in));
+
        throws IOException
 
+
    {
        System.out.println("Enter dirpath:");
+
        // enter the path and dirname from keyboard
        String dirpath = br.readLine();
+
        BufferedReader br = new BufferedReader(
        System.out.println("Enter the dirname");
+
            new InputStreamReader(System.in));
        String dname = br.readLine();
+
 
 
+
        System.out.println("Enter dirpath:");
        // create File object with dirpath and dname
+
        String dirpath = br.readLine();
        File f = new File(dirpath, dname);
+
        System.out.println("Enter the dirname");
 
+
        String dname = br.readLine();
        // if directory exists,then
+
 
        if (f.exists()) {
+
        // create File object with dirpath and dname
            // get the contents into arr[]
+
        File f = new File(dirpath, dname);
            // now arr[i] represent either a File or
+
 
            // Directory
+
        // if directory exists,then
            String arr[] = f.list();
+
        if (f.exists()) {
 
+
            // get the contents into arr[]
            // find no. of entries in the directory
+
            // now arr[i] represent either a File or
            int n = arr.length;
+
            // Directory
 
+
            String arr[] = f.list();
            // displaying the entries
+
 
            for (int i = 0; i < n; i++) {
+
            // find no. of entries in the directory
                System.out.println(arr[i]);
+
            int n = arr.length;
                // create File object with the entry and
+
 
                // test if it is a file or directory
+
            // displaying the entries
                File f1 = new File(arr[i]);
+
            for (int i = 0; i < n; i++) {
                if (f1.isFile())
+
                System.out.println(arr[i]);
                    System.out.println(": is a file");
+
                // create File object with the entry and
                if (f1.isDirectory())
+
                // test if it is a file or directory
                    System.out.println(": is a directory");
+
                File f1 = new File(arr[i]);
            }
+
                if (f1.isFile())
            System.out.println(
+
                    System.out.println(": is a file");
                "No of entries in this directory " + n);
+
                if (f1.isDirectory())
        }
+
                    System.out.println(": is a directory");
        else
+
            }
            System.out.println("Directory not found");
+
            System.out.println(
    }
+
                "No of entries in this directory " + n);
}
+
        }
 +
        else
 +
            System.out.println("Directory not found");
 +
    }
 +
}
 +
 
 
Output:  
 
Output:  
 
+
Enter dirpath:
Enter dirpath:
+
C:\Users\akki\IdeaProjects\
C:\Users\akki\IdeaProjects\
+
Enter the dirname
Enter the dirname
+
codewriting
codewriting
+
.idea
.idea
+
: is a directory
: is a directory
+
an1.txt
an1.txt
+
: is a file
: is a file
+
codewriting.iml
codewriting.iml
+
: is a file
: is a file
+
file.txt
file.txt
+
: is a file
: is a file
+
out
out
+
: is a directory
: is a directory
+
src
src
+
: is a directory
: is a directory
+
text
text
+
: is a file
: is a file
+
No of entries in this directory 7
No of entries in this directory 7
 

Latest revision as of 13:29, 7 May 2022

Class File adalah representasi Java dari pathname file atau direktori. Karena nama file dan direktori memiliki format yang berbeda pada platform yang berbeda, string sederhana tidak cukup untuk menamainya. Class File berisi beberapa method untuk bekerja dengan pathname, menghapus dan mengganti nama file, membuat direktori baru, membuat daftar isi direktori, dan menentukan beberapa atribut umum dari file dan direktori.

  • Ini adalah representasi abstrak dari file dan pathname direktori.
  • pathname, apakah abstrak atau dalam bentuk string dapat berupa absolut atau relatif. Induk dari pathname abstrak dapat diperoleh dengan memanggil metode getParent() dari Class ini.
  • Pertama-tama, kita harus membuat object Class File dengan meneruskan nama file atau nama direktori ke sana. Sistem file dapat menerapkan pembatasan operasi tertentu pada objek sistem file yang sebenarnya, seperti membaca, menulis, dan mengeksekusi. Pembatasan ini secara kolektif dikenal sebagai izin akses.
  • Contoh Class File tidak dapat diubah; yaitu, setelah dibuat, pathname abstrak yang diwakili oleh object File tidak akan pernah berubah.


Bagaimana cara membuat Object File?

Object File dibuat dengan meneruskan string yang mewakili nama file, String, atau objek File lainnya. Sebagai contoh,

File a = new File("/usr/local/bin/geeks");

Ini mendefinisikan nama file abstrak untuk file Geeks di direktori /usr/local/bin. Ini adalah nama file abstrak yang bersifat absolut.


Constructors of File Class

  • File(File parent, String child): Buat instance new file dari parent abstract pathname dan child pathname string.
  • File(String pathname): Buat instance new File dengan cara mengubah pathname string yang diberikan menjadi abstract pathname.
  • File(String parent, String child): Buat instance new File dari parent pathname string dan child pathname string.
  • File(URI uri): Buat instance new File dengan cara mengubah file: URI yang diberikan menjadi abstract pathname.

Method dari File Class

No.	Method		Description										Return Type
1.	canExecute()	Tests whether the application can execute the file denoted by this abstract pathname.	boolean
2.	canRead()	Tests whether the application can read the file denoted by this abstract pathname.	boolean
3.	canWrite()	Tests whether the application can modify the file denoted by this abstract pathname.	boolean
4.	compareTo(File pathname)	Compares two abstract pathnames lexicographically.			int
5.	createNewFile()	Atomically creates a new, empty file named by this abstract pathname.			boolean
6.	createTempFile(String prefix, String suffix)	Creates an empty file in the default temporary-file directory.	File
7.	delete()	Deletes the file or directory denoted by this abstract pathname.			boolean
8.	equals(Object obj)	Tests this abstract pathname for equality with the given object.		boolean
9.	exists()	Tests whether the file or directory denoted by this abstract pathname exists.		boolean
10.	getAbsolutePath()	 Returns the absolute pathname string of this abstract pathname.		String
11.	list()	Returns an array of strings naming the files and directories in the directory.			String[]
12.	getFreeSpace()	Returns the number of unallocated bytes in the partition.				long
13.	getName()	Returns the name of the file or directory denoted by this abstract pathname.		String
14.	getParent()	Returns the pathname string of this abstract pathname’s parent.				String
15.	getParentFile()	Returns the abstract pathname of this abstract pathname’s parent.			File
16.	getPath()	Converts this abstract pathname into a pathname string.					String
17.	setReadOnly()	Marks the file or directory named so that only read operations are allowed.		boolean
18.	isDirectory()	Tests whether the file denoted by this pathname is a directory.				boolean
19.	isFile()	Tests whether the file denoted by this abstract pathname is a normal file.		boolean
20.	isHidden()	Tests whether the file named by this abstract pathname is a hidden file.		boolean
21.	length()	Returns the length of the file denoted by this abstract pathname.			long
22.	listFiles()	Returns an array of abstract pathnames denoting the files in the directory.		File[]
23.	mkdir()	Creates the directory named by this abstract pathname.						boolean
24.	renameTo(File dest)	Renames the file denoted by this abstract pathname.				boolean
25.	setExecutable(boolean executable)	A convenience method to set the owner’s execute permission.	boolean
26.	setReadable(boolean readable)	A convenience method to set the owner’s read permission.		boolean
27.	setReadable(boolean readable, boolean ownerOnly)	Sets the owner’s or everybody’s read permission.boolean
28.	setWritable(boolean writable)	A convenience method to set the owner’s write permission.		boolean
29.	toString()	Returns the pathname string of this abstract pathname.					String
30.	toURI()		Constructs a file URI that represents this abstract pathname.				URI

Example 1: Program to check if a file or directory physically exists or not.

// In this Java program, we accepts a file or directory name from
// command line arguments. Then the program will check if
// that file or directory physically exist or not and
// it displays the property of that file or directory.
  
import java.io.File;
  
// Displaying file property
class fileProperty {
    public static void main(String[] args)
    {
  
        // accept file name or directory name through
        // command line args
        String fname = args[0];
  
        // pass the filename or directory name to File
        // object
        File f = new File(fname);
  
        // apply File class methods on File object
        System.out.println("File name :" + f.getName());
        System.out.println("Path: " + f.getPath());
        System.out.println("Absolute path:"
                           + f.getAbsolutePath());
        System.out.println("Parent:" + f.getParent());
        System.out.println("Exists :" + f.exists());
  
        if (f.exists()) {
            System.out.println("Is writable:"
                               + f.canWrite());
            System.out.println("Is readable" + f.canRead());
            System.out.println("Is a directory:"
                               + f.isDirectory());
            System.out.println("File Size in bytes "
                               + f.length());
        }
    }
}

Output:

File name :file.txt
Path: file.txt
Absolute path:C:\Users\akki\IdeaProjects\codewriting\src\file.txt
Parent:null
Exists :true
Is writable:true
Is readabletrue
Is a directory:false
File Size in bytes 20

Example 2: Program to display all the contents of a directory

Di sini kita akan menerima nama direktori dari keyboard dan kemudian menampilkan semua isi direktori. Untuk tujuan ini, method list() dapat digunakan sebagai berikut:


String arr[]=f.list();

Dalam pernyataan sebelumnya, metode list() menyebabkan semua entri direktori disalin ke dalam array arr[]. Kemudian berikan elemen array ini arr[i] ke objek File dan uji untuk mengetahui apakah elemen tersebut mewakili file atau direktori.

// Java Program to display all 
// the contents of a directory
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
  
// Displaying the contents of a directory
class Contents {
    public static void main(String[] args)
        throws IOException
    {
        // enter the path and dirname from keyboard
        BufferedReader br = new BufferedReader(
            new InputStreamReader(System.in));
  
        System.out.println("Enter dirpath:");
        String dirpath = br.readLine();
        System.out.println("Enter the dirname");
        String dname = br.readLine();
  
        // create File object with dirpath and dname
        File f = new File(dirpath, dname);
  
        // if directory exists,then
        if (f.exists()) {
            // get the contents into arr[]
            // now arr[i] represent either a File or
            // Directory
            String arr[] = f.list();
  
            // find no. of entries in the directory
            int n = arr.length;
  
            // displaying the entries
            for (int i = 0; i < n; i++) {
                System.out.println(arr[i]);
                // create File object with the entry and
                // test if it is a file or directory
                File f1 = new File(arr[i]);
                if (f1.isFile())
                    System.out.println(": is a file");
                if (f1.isDirectory())
                    System.out.println(": is a directory");
            }
            System.out.println(
                "No of entries in this directory " + n);
        }
        else
            System.out.println("Directory not found");
    }
}

Output:

Enter dirpath:
C:\Users\akki\IdeaProjects\
Enter the dirname
codewriting
.idea
: is a directory
an1.txt
: is a file
codewriting.iml
: is a file
file.txt
: is a file
out
: is a directory
src
: is a directory
text
: is a file
No of entries in this directory 7