Search code examples
javafileio

Create new file - Getting IOException


I'm trying to create a settings file for my program, but when I debug the program, I get an IOException.

Here's the code I'm using.

// Universal Android Toolkit
String docs = new String(System.getProperty("user.home"));
String uatDocs = docs + "/Team_M4gkBeatz/Universal_Android_Toolkit";
// Settings
File sets = new File(uatDocs + "/Settings/Settings_uat.uatsavefile");

private void createSettings()
{
    try
    {
        jProgressBar1.setValue(0);
        progress += "Creating settings file... ";
        jTextArea2.setText(progress);
        sets.createNewFile();
        Thread.sleep(3000);
        progress += "Done.\nLoading UI...\n";
        jTextArea2.setText(progress);
        jProgressBar1.setValue(100);
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "ERROR: There was an error while creating the settings file.\n" + ex + "\nPlease report this error to the developer/s.\nThe application will now close.", "Error Creating Settings File", JOptionPane.ERROR_MESSAGE);
        System.exit(0);
    }
}

What am I doing wrong?


Solution

  • Looks like you haven't upper folder

    System.getProperty("user.home") + "/Team_M4gkBeatz/Universal_Android_Toolkit/Settings"
    

    so you cann't create the file. So you should check it and create folders:

    final File parentDirectory = sets.getParentFile();
    if (!parentDirectory.exists()) // checks that directory exists
    {
       parentDirectory.mkdirs();   
    }
    if (!sets.exists()) // checks that file exists
    {
       sets.createNewFile();
    }