Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

Create a Text File in Java

Using java.io.File package you can create a text file. See the example below. 

 

package com.seleniummaster.examplefile;
import java.io.File;
import java.io.IOException;

public class CreateFile {

    public static void main(String[] args)
    {
        CreateNewFile("test1.txt");
    }

//Create a new file
    public static void CreateNewFile(String filename) {
        //get current project path
        String filePath = System.getProperty("user.dir");
        //create a new file
        File file = new File(filePath + "\\" + filename);

        try {
            if (!file.exists()) {
                file.createNewFile();
                System.out.println("File is created");
            } else {
                System.out.println("File already exist");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    }

Run the code and see the result below. A file "test1.txt" is created.

File is created

Process finished with exit code 0

If you run the code again, you will see File already exist text

File already exist

Process finished with exit code 0