GuaranteeAFile.java Source code

Java tutorial

Introduction

Here is the source code for GuaranteeAFile.java

Source

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;

public class GuaranteeAFile {
    public static void main(String[] args) {

        String filename = "C:/myFile.txt";
        File aFile = new File(filename);
        if (aFile.isDirectory()) {
            System.out.println("The path " + aFile.getPath() + " does not specify a file. Program aborted.");
            System.exit(1);
        }
        if (!aFile.isFile()) {
            aFile = aFile.getAbsoluteFile();
            File parentDir = new File(aFile.getParent());
            if (!parentDir.exists()) {
                parentDir.mkdirs();
            }
        }
        FileOutputStream outputFile = null;
        try {
            outputFile = new FileOutputStream(aFile, true);
        } catch (FileNotFoundException e) {
            e.printStackTrace(System.err);
        }
    }
}