HOME HTML EDITOR C JAVA PHP

Java File Methods

In Java, the File class is used to create, read, write, and manage files. It is part of the java.io package.

File handling is very important in Java because it allows programs to store data permanently.

1. Importing File Class

import java.io.File;

2. Creating a File Object

To work with a file, we first create a File object.

File file = new File("example.txt");

3. createNewFile()

The createNewFile() method creates a new file. It returns true if the file is created successfully.

import java.io.File; import java.io.IOException; File file = new File("example.txt"); try { if (file.createNewFile()) { System.out.println("File created successfully."); } else { System.out.println("File already exists."); } } catch (IOException e) { System.out.println("An error occurred."); }

4. exists()

The exists() method checks whether a file exists.

if(file.exists()) { System.out.println("File exists."); }

5. getName()

The getName() method returns the file name.

System.out.println(file.getName());

6. getAbsolutePath()

The getAbsolutePath() method returns the full path of the file.

System.out.println(file.getAbsolutePath());

7. length()

The length() method returns the size of the file in bytes.

System.out.println(file.length());

8. delete()

The delete() method deletes a file.

if(file.delete()) { System.out.println("File deleted successfully."); }

9. canRead() and canWrite()

canRead() checks if the file is readable. canWrite() checks if the file is writable.

System.out.println(file.canRead()); System.out.println(file.canWrite());

10. isFile() and isDirectory()

isFile() checks if it is a file. isDirectory() checks if it is a folder.

System.out.println(file.isFile()); System.out.println(file.isDirectory());

Reading Data from File

To read data from a file, we use Scanner with File.

import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; File file = new File("example.txt"); Scanner sc = new Scanner(file); while(sc.hasNextLine()) { String data = sc.nextLine(); System.out.println(data); } sc.close();

Writing Data to File

To write data into a file, we use FileWriter.

import java.io.FileWriter; import java.io.IOException; try { FileWriter writer = new FileWriter("example.txt"); writer.write("Hello Java File Handling"); writer.close(); System.out.println("Data written successfully."); } catch (IOException e) { System.out.println("An error occurred."); }

Important Points

Conclusion

The File class provides useful methods like createNewFile(), exists(), delete(), getName(), and more.

Java file handling is very important for storing and managing data permanently.

Tip: Always use proper exception handling while working with files.