Creating file and temp file

3 0 0
                                    

Files.createFile(Path, FileAttribute<T>) - This method creates an empty file and throws an exception if the file already exist. You can also set the permission using the FileAttribute<T> which is optional.

================

class PracticingCreateFile{

    public static void main(String[] args) throws IOException{

        try{

            String fileName = "TemporaryDocumentText.txt";

            Path path = Paths.get(fileName);

            if(Files.exist(path)){

                throw FileAlreadyExistsException("This " + fileName + "does exist!");

            }else {

                Files.createFile(path)

                System.out.println("This " + fileName + was created successfully.);

            }

        }catch(FileAlreadyExistsException f){

            System.err.println(f.getMessage());

        }

    }

}

================

Result:

This TemporaryDocumentText.txt was created successfully.

Note: The first time you run, if file doesn't exist, it will create the file. The second time you run, it will throw the FileAlreadyExistsException.


Creating Temporary File

1. Files.createTempFile(path, String, String, FileAttriute<T>)

2. Files.createTempFile(String, String, FileAttriute<T>)

Java ProgrammingWhere stories live. Discover now