Top News

Java File Creation -01

 

Java File Creation

In java Language files are used to do various works. files are very important part of many applications. we can create, Read, Update and delete the data from the files. in Java we have to add package to access the Files.



“ java.io” allows us to work with different formats of files. In order to use the File class, you need to create an object of the class and specify the filename or directory name. A file is a named location that can be used to store related information.

Java File Operation Methods

Operation

Method

Package

To create file

createNewFile()

java.io.File

To read file

read()

java.io.FileReader

To write file

write()

java.io.FileWriter

To delete file

delete()

java.io.File

  

Sample Code for creating files

// importing the File class

import java.io.File;

class Main {

  public static void main(String[] args) {

    // create a file object for the current location

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

    try {

      // trying to create a file based on the object

      boolean value = file.createNewFile();

      if (value) {

        System.out.println("The new file is created.");

      }

      else {

        System.out.println("The file already exists.");

      }

    }

    catch(Exception e) {

      e.getStackTrace();

    }

  }

}

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

we have used the file object to create the new file with the specified path.



in the current location if the file is does not exist the new file will create .




 if exist message will thrown like file already available.



Why Use getStackTrace()?

  1. Programmatic Access: You can analyze the stack trace programmatically, which is useful for logging, debugging, or performing specific error handling.
  2. Custom Error Handling: You might want to iterate through the stack trace elements to filter, format, or log them differently than the default output.
  3. Enhanced Debugging: By examining the stack trace, developers can trace the sequence of method calls leading to an error, which is invaluable for diagnosing issues.

in the code we can see there is a folder name called flex. in that folder only java file exist. before run the code only java file is there. once run the file ourfilename will be created in that folder. so this the method creating java file. in our next post we will study about enter data into the file.



 appreciate you taking the time to read this post. Don't forget to check back for more interesting content in the near future. See you next time!

Post a Comment

Previous Post Next Post