The File class (java.io.File) is used to represent files and directories. A constructor is used to create a File object that points to a file or folder.
1. File(String pathname)
Syntax
File file = new File(String pathname);
Purpose
Creates a File object using a single path string.
Example
import java.io.File;
public class Demo {
public static void main(String[] args) {
File file = new File("sample.txt");
System.out.println(file.getPath());
}
}
Output
sample.txt
Explanation
File file = new File("sample.txt");
Creates a File object named file.
Represents the file sample.txt.
The file is not created physically; only the object is created.
2. File(String parent, String child)
Syntax
File file = new File(parent, child);
Purpose
Creates a file by combining a parent directory and a child file name.
Example
import java.io.File;
public class Demo {
public static void main(String[] args) {
File file = new File("C:\\Users\\Priya", "sample.txt");
System.out.println(file.getPath());
}
}
Output
C:\Users\Priya\sample.txt
Explanation
"C:\Users\Priya"
→ Parent directory
"sample.txt"
→ Child file
Java combines both:
C:\Users\Priya\sample.txt
3. File(File parent, String child)
Syntax
File parent = new File("C:\\Users\\Priya");
File file = new File(parent, "sample.txt");
Purpose
Uses an existing File object as the parent directory.
Example
import java.io.File;
public class Demo {
public static void main(String[] args) {
File parentFolder = new File("C:\\Users\\Priya");
File file = new File(parentFolder, "sample.txt");
System.out.println(file.getPath());
}
}
Output
C:\Users\Priya\sample.txt
Explanation
Step 1:
File parentFolder = new File("C:\\Users\\Priya");
Creates a File object representing the folder.
Step 2:
File file = new File(parentFolder, "sample.txt");
Adds sample.txt inside that folder.
4. File(URI uri)
Syntax
File file = new File(URI uri);
Purpose
Creates a File object from a URI (Uniform Resource Identifier).
Example
import java.io.File;
import java.net.URI;
public class Demo {
public static void main(String[] args) {
URI uri = URI.create("file:///C:/Users/Priya/sample.txt");
File file = new File(uri);
System.out.println(file.getPath());
}
}
Output
C:\Users\Priya\sample.txt
Explanation
URI uri = URI.create("file:///C:/Users/Priya/sample.txt");
Creates a URI object.
new File(uri);
Converts the URI into a File object.
Important Note
File file = new File("sample.txt");
does not create the actual file.
To create the file physically, use:
file.createNewFile();
Example:
import java.io.File;
import java.io.IOException;
public class Demo {
public static void main(String[] args) throws IOException {
File file = new File("sample.txt");
file.createNewFile();
System.out.println("File created");
}
}
Output
File created
Thus, constructors create only the File object (abstract pathname), not the actual file itself.
Top comments (0)