创建新文件 - 获取IOException

时间:2013-11-02 19:56:46

标签: java file io

我正在尝试为我的程序创建一个设置文件,但是当我调试程序时,我得到一个IOException。

这是我正在使用的代码。

// 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);
    }
}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

看起来你没有上层文件夹

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

因此您无法创建该文件。所以你应该检查它并创建文件夹:

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