0
How to use File class
Introduction to File
File is a class which belongs to java.io package. As the name suggests File class can be used to point a File as well as a folder stored in any storage device.
How to use File class
- To check the availability of folder or file.
- To check the permission of folder or file.
- To create a blank file.
- To create a stream which points to specific named file which can be used to read/write some data
Program to create a new blank file.
File Name: CreateBlankFile.java
import java.io.*; class CreateBlankFile { public static void main(String[] s) throws IOException { File f = new File("myFile.txt"); f.createNewFile(); System.out.println("File created!"); } }
Retrieve file information
File Name: FileMethodDemo.java
import java.io.File; class FileMethodDemo { public static void main(String args[]) { File f1 = new File("myFile.txt"); System.out.println("File Name: " + f1.getName()); System.out.println("Path: " + f1.getPath()); System.out.println("Abs Path: " + f1.getAbsolutePath()); System.out.println("Parent: " + f1.getParent()); System.out.println(f1.exists() ? "exists" : "does not exist"); System.out.println(f1.canWrite() ? "is writeable" : "is not writeable"); System.out.println(f1.canRead() ? "is readable" : "is not readable"); System.out.println("is " + (f1.isDirectory() ? "" : "not" + " a directory")); System.out.println(f1.isFile() ? "is normal file" : "might be a named pipe"); System.out.println(f1.isAbsolute() ? "is absolute" : "is not absolute"); System.out.println("File last modified: " + f1.lastModified()); System.out.println("File size: " + f1.length() + " Bytes"); } }
Recent Comments