Search code examples
javamacosfilesystemsclassnotfoundcreate-directory

Create folder on OS X


I have one code to create Folder into the Mac OS

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.File;
import java.net.URL;

/**
 *
 * @author kishan
 */
public class CreatingMacFile {
    public static void main(String[] args){

        boolean check = new CreatingMacFile().makefile();
        if (check) {
            System.out.println("file created");
        }else{
            System.out.println("file is not created");
        }
    }


    public boolean makefile() {
        try {

            String resource = CreatingMacFile.class.getName().replace(".", File.separator) + ".class";
            URL fileURL = ClassLoader.getSystemClassLoader().getResource(resource);

            String path = new File(fileURL.toURI()).getParent();
            System.out.println("this is path that we getting: "+path);
            String mySubFolder = "subFolder";
            File newDir = new File(path + File.separator + mySubFolder);

            System.out.println("File Path: "+newDir.getAbsolutePath());

            boolean success = newDir.mkdir();

            if (success) {
                return true;
            }else{
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

but i am getting error of noClassFound

what i am missing?

stacktrace

Exception in thread "main" java.lang.NoClassDefFoundError: CreatingMacFile
Caused by: java.lang.ClassNotFoundException: CreatingMacFile
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)

Solution

  • Class<?> c = ...
    File file = new File("/tmp/", c.getName().replaceAll("\\.", File.separator));
    file.mkdirs();
    

    Note the mkdirs() method (with an ending s). HTH.