Java Code Examples for java.io.File.mkdirs()

The following are Jave code examples for showing how to use mkdirs() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Aurora   File: CacheDownLoadService.java   View Source Code Vote up 7 votes
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent.getBooleanExtra(PAUSE_DOWNLOAD, false)) {
        queue.pause();
        return START_REDELIVER_INTENT;
    }
    VideoDownLoadInfo video = (VideoDownLoadInfo) intent.getSerializableExtra(VIDEOS_INFO);
    EventBus.getDefault().postSticky(video,EventBusTags.CACHE_DOWNLOAD_BEGIN);
    videos.put(video.getId()+"",video);
    File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Sunny_Videos");
    if (!dir.exists()) {
        dir.mkdirs();
    }
    DaoMaster master = GreenDaoHelper.getInstance().create(video.getDbName()).getMaster();
    master.newSession().startAsyncSession().insertOrReplace(video);
    File file = new File(dir.getAbsolutePath(), video.getId() + ".mp4");
    BaseDownloadTask task = (FileDownloader.getImpl().create(video.getVideo().getPlayUrl()).setPath(file.getAbsolutePath()).setTag(video.getId()+""));
    task.setListener(new CommonDownloadListener());
    queue.enqueue(task);
    if (isInit){
        queue.resume();
        isInit = false;
    }
    return START_NOT_STICKY;
}
 
Example 2
Project: openjdk-jdk10   File: JImageTask.java   View Source Code Vote up 6 votes
private void extract(BasicImageReader reader, String name,
        ImageLocation location) throws IOException, BadArgs {
    File directory = new File(options.directory);
    byte[] bytes = reader.getResource(location);
    File resource =  new File(directory, name);
    File parent = resource.getParentFile();

    if (parent.exists()) {
        if (!parent.isDirectory()) {
            throw TASK_HELPER.newBadArgs("err.cannot.create.dir",
                                        parent.getAbsolutePath());
        }
    } else if (!parent.mkdirs()) {
        throw TASK_HELPER.newBadArgs("err.cannot.create.dir",
                                    parent.getAbsolutePath());
    }

    if (!ImageResourcesTree.isTreeInfoResource(name)) {
        Files.write(resource.toPath(), bytes);
    }
}
 
Example 3
Project: Winter   File: InfoConsumer.java   View Source Code Vote up 6 votes
private File createFile() {
    String dir = Environment.getExternalStorageDirectory() + "/winter/monitor";
    File dirFile = new File(dir);
    if (!dirFile.exists()) {
        dirFile.mkdirs();
    }
    SimpleDateFormat dateformat1 = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.CHINESE);
    String a1 = dateformat1.format(new Date());
    File file = new File(dir + "/" + a1 + ".log");
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return file;
}
 
Example 4
Project: monarch   File: CacheXml66DUnitTest.java   View Source Code Vote up 6 votes
/**
 * @since GemFire 4.3
 */
@Test
public void testDynamicRegionFactoryDiskDir() throws CacheException {
  CacheCreation cache = new CacheCreation();
  File f = new File("diskDir");
  f.mkdirs();
  cache.setDynamicRegionFactoryConfig(new DynamicRegionFactory.Config(f, null, true, true));
  RegionAttributesCreation attrs = new RegionAttributesCreation(cache);
  cache.createRegion("root", attrs);
  // note that testXml can't check if they are same because enabling
  // dynamic regions causes a meta region to be produced.
  testXml(cache, false);
  assertEquals(true, DynamicRegionFactory.get().isOpen());
  assertEquals(f.getAbsoluteFile(), DynamicRegionFactory.get().getConfig().getDiskDir());
  Region dr = getCache().getRegion("__DynamicRegions");
  if (dr != null) {
    dr.localDestroyRegion();
  }
}
 
Example 5
Project: react-native-geth   File: GethHolder.java   View Source Code Vote up 6 votes
protected void writeStaticNodesFile(String enodes) {
    try {
        File dir = new File(this.reactContext
                .getFilesDir() + STATIC_NODES_FILES_PATH);
        if (dir.exists() == false) dir.mkdirs();
        File f = new File(dir, STATIC_NODES_FILES_NAME);
        if (f.exists() == false) {
            if (f.createNewFile() == true) {
                WritableArray staticNodes = new WritableNativeArray();
                staticNodes.pushString(enodes);
                Writer output = new BufferedWriter(new FileWriter(f));
                output.write(staticNodes.toString());
                output.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 6
Project: EVideoRecorder   File: StorageUtils.java   View Source Code Vote up 6 votes
private static File getExternalCacheDir(Context context, String name) {
    File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
    File appCacheDir = new File(new File(dataDir, context.getPackageName()), "name");
    if (!appCacheDir.exists()) {
        if (!appCacheDir.mkdirs()) {
            return null;
        }

        try {
            (new File(appCacheDir, ".nomedia")).createNewFile();
        } catch (IOException var4) {
        }
    }

    return appCacheDir;
}
 
Example 7
Project: hadoop   File: TestClusterId.java   View Source Code Vote up 6 votes
/**
 * Test namenode format with -format -nonInteractive options when a non empty
 * name directory exists. Format should not succeed.
 * 
 * @throws IOException
 */
@Test
public void testFormatWithNonInteractive() throws IOException {

  // we check for a non empty dir, so create a child path
  File data = new File(hdfsDir, "file");
  if (!data.mkdirs()) {
    fail("Failed to create dir " + data.getPath());
  }

  String[] argv = { "-format", "-nonInteractive" };
  try {
    NameNode.createNameNode(argv, config);
    fail("createNameNode() did not call System.exit()");
  } catch (ExitException e) {
    assertEquals("Format should have been aborted with exit code 1", 1,
        e.status);
  }

  // check if the version file does not exists.
  File version = new File(hdfsDir, "current/VERSION");
  assertFalse("Check version should not exist", version.exists());
}
 
Example 8
Project: World-Border   File: Config.java   View Source Code Vote up 5 votes
public static void setupConfigDir(File globalDir)
{
    configDir = new File(globalDir, WorldBorder.MODID);

    if ( !configDir.exists() && configDir.mkdirs() )
        Log.info("Created config directory for the first time");
}
 
Example 9
Project: incubator-netbeans   File: NbStartLocalTest.java   View Source Code Vote up 5 votes
@org.junit.Test
public void testShellCommandProcess() throws Exception {
    NativeProcessBuilder npb = NativeProcessBuilder.newLocalProcessBuilder();
    File out = new File(getWorkDirPath(), "testShellCommandProcess");
    out.mkdirs();
    out.delete();
    try {
        npb.setCommandLine("echo TEST > \"" + out.getAbsolutePath() + "\"");
        NativeProcess process = npb.call();
        int rc = process.waitFor();

        if (!(process instanceof NbNativeProcess)) {
            System.out.println("Test testShellCommandProcess is not applicable for " + process.getClass().getName() + " - skipped");
            return;
        }


        assertEquals("echo with redirection status", 0, rc);

        BufferedReader br = new BufferedReader(new FileReader(out));
        StringBuilder sb = new StringBuilder();

        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        assertEquals("TEST is expected to be written in " + out.getAbsolutePath(), "TEST", sb.toString().trim());
    } finally {
        out.delete();
    }
}
 
Example 10
Project: dex-hdog   File: FileUtil.java   View Source Code Vote up 5 votes
public static boolean createPath(String pathName){
    File file = new File(pathName);
    if(!file.exists()){
        boolean suc = file.mkdirs();
        return suc;
    }else{
        return true;
    }
}
 
Example 11
Project: mybatis-generator-plugin   File: AbstractShellCallback.java   View Source Code Vote up 5 votes
public File getDirectory(String targetProject, String targetPackage) throws ShellException {
    // targetProject is interpreted as a directory that must exist
    //
    // targetPackage is interpreted as a sub directory, but in package
    // format (with dots instead of slashes). The sub directory will be
    // created
    // if it does not already exist

    File project = new File(targetProject);
    if (!project.isDirectory()) {
        throw new ShellException(getString("Warning.9", targetProject));
    }

    StringBuilder sb = new StringBuilder();
    StringTokenizer st = new StringTokenizer(targetPackage, ".");
    while (st.hasMoreTokens()) {
        sb.append(st.nextToken());
        sb.append(File.separatorChar);
    }

    File directory = new File(project, sb.toString());
    if (!directory.isDirectory()) {
        boolean rc = directory.mkdirs();
        if (!rc) {
            throw new ShellException(getString("Warning.10", directory.getAbsolutePath()));
        }
    }

    return directory;
}
 
Example 12
Project: Android-Scrapper   File: DatabaseDump.java   View Source Code Vote up 5 votes
@SuppressWarnings("ResultOfMethodCallIgnored")
private void saveDatabase(String jsonData) {
    try {
        File cachePath = new File(TallyStackerApplication.get().getCacheDir(), CHILD);
        cachePath.mkdirs();
        FileOutputStream stream = new FileOutputStream(cachePath + "/" + DATABASE_NAME);
        BufferedOutputStream bos = new BufferedOutputStream(stream);

        Exporter mExporter = new Exporter(bos);
        mExporter.writeJson(jsonData);
        mExporter.close();
        stream.close();
        File newFile = new File(cachePath, DATABASE_NAME);
        Uri contentUri = FileProvider.getUriForFile(mContext, "com.calebtrevino.tallystacker.file_provider", newFile);
        if (contentUri != null) {
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
            shareIntent.putExtra(Intent.EXTRA_SUBJECT, "TallyStacker Database");
            shareIntent.putExtra(Intent.EXTRA_TEXT, "Please have a look");
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
            shareIntent.setType(mContext.getContentResolver().getType(contentUri));
            mContext.startActivity(Intent.createChooser(shareIntent, mContext.getResources().getText(R.string.send_to)));
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 13
Project: starcor.xul   File: XulSystemUtil.java   View Source Code Vote up 5 votes
private static String getExternalCacheDir(Context context) {
    File dir = context.getExternalCacheDir();
    if (dir == null) {
        return null;
    }
    if (!dir.mkdirs() && !dir.exists()) {
        return null;
    }
    return dir.getPath();
}
 
Example 14
Project: chipKIT-importer   File: ImportWorker.java   View Source Code Vote up 5 votes
private File initProjectDirectoryFromWizard(Set<FileObject> projectRootDirectories) {
    File projectDirectory = (File) wizardDescriptor.getProperty(WizardProperty.PROJECT_DIR.key());
    if (projectDirectory != null) {
        projectDirectory = FileUtil.normalizeFile(projectDirectory);
    }
    projectDirectory.mkdirs();
    FileObject dir = FileUtil.toFileObject(projectDirectory);
    projectRootDirectories.add(dir);
    return projectDirectory;
}
 
Example 15
Project: decoy   File: NIMGlideModule.java   View Source Code Vote up 5 votes
private static synchronized DiskCache createDiskCache() {
    final Context context = NimUIKit.getContext();
    File cacheDir = StorageUtils.getOwnCacheDirectory(context, context.getPackageName() + "/cache/image/");
    if (!cacheDir.exists()) {
        cacheDir.mkdirs();
    }
    return DiskLruCacheWrapper.get(cacheDir, MAX_DISK_CACHE_SIZE);
}
 
Example 16
Project: hadoop   File: TestLdapGroupsMapping.java   View Source Code Vote up 5 votes
@Test
public void testExtractPassword() throws IOException {
  File testDir = new File(System.getProperty("test.build.data", 
                                             "target/test-dir"));
  testDir.mkdirs();
  File secretFile = new File(testDir, "secret.txt");
  Writer writer = new FileWriter(secretFile);
  writer.write("hadoop");
  writer.close();
  
  LdapGroupsMapping mapping = new LdapGroupsMapping();
  Assert.assertEquals("hadoop",
      mapping.extractPassword(secretFile.getPath()));
}
 
Example 17
Project: atlas   File: DexPatchProguardTask.java   View Source Code Vote up 5 votes
private File getOutJar(File file) {
    File folder = new File(variantContext.getVariantData().getScope().getGlobalScope().getOutputsDir(),"proguard");
    if (!folder.exists()){
        folder.mkdirs();
    }
    return new File(folder, MD5Util.getFileMD5(file)+"-proguard.jar");

}
 
Example 18
Project: AdvancedDataProfilingSeminar   File: Sindd.java   View Source Code Vote up 4 votes
private static void createDirectory(File dirFile) {
  dirFile.mkdirs();
}
 
Example 19
Project: incubator-netbeans   File: ShorterPathsTest.java   View Source Code Vote up 4 votes
/** Tests that if an extra library has Class-Path attribute (extlib.jar), 
 * then extra jar (ext/ext/cpext1.jar) is copied to binary distribution
 * (extralibs) with proper relative path.
 */
public void testClassPathExtensions() throws Exception {
    // create test
    File wd = getWorkDir();
    File modules = new File(wd, "modules");
    modules.mkdirs();
    File module = new File(modules, "module.jar");
    module.createNewFile();
    File extraLibsDir = new File(wd, "extralibs");
    File testProperties = new File(wd, "outtest.properties");
    extraLibsDir.mkdirs();

    // create ext lib with Class-Path extension
    String cpExtensionRelativePath = "ext/ext/cpext1.jar";
    File classPathExtension = new File(getWorkDir(), cpExtensionRelativePath);
    classPathExtension.getParentFile().mkdirs();
    classPathExtension.createNewFile();
    Manifest m = createManifest();
    m.getMainAttributes().putValue("Class-Path", cpExtensionRelativePath);
    File extlib = new File(getWorkDir(), "extlib.jar");
    generateJar(extlib, new String[]{"a/b/c/Class1.class", "a/b/c/Class2.class"}, m);

    execute("ShorterPathsTest.xml", new String[]{
                "-verbose",
                "-Dtest.ext.lib=" + extlib.getPath(),
                "-Dtest.modules.dir=" + modules.getPath(),
                "-Dextra.test.libs.dir=" + extraLibsDir.getPath(),
                "-Dtest.properties=" + testProperties.getPath(),
                "all"
            });
    File extralibCopy = new File(extraLibsDir, "extlib.jar");
    assertTrue("Extra library not copied.", extralibCopy.exists());
    File classPathExtensionCopy = new File(extraLibsDir, cpExtensionRelativePath);
    assertTrue("Class-Path extension not copied.", classPathExtensionCopy.exists());

    Properties props = new Properties();
    try (FileInputStream propsIs = new FileInputStream(testProperties)) {
        props.load(propsIs);
    }
    assertEquals("extra.test.libs.dir", "${extra.test.libs.dir}/extlib.jar", props.getProperty("extra.test.libs"));
    assertEquals("test.run.cp", "${nb.root.test.dir}/module.jar", props.getProperty("test.run.cp"));
}
 
Example 20
Project: WePush   File: Init.java   View Source Code Vote up 4 votes
/**
 * 初始化设置tab
 */
public static void initSettingTab() {
    // 微信
    MainWindow.mainWindow.setWechatAppIdTextField(configer.getWechatAppId());
    MainWindow.mainWindow.setWechatAppSecretPasswordField(configer.getWechatAppSecret());
    MainWindow.mainWindow.setWechatTokenPasswordField(configer.getWechatToken());
    MainWindow.mainWindow.setWechatAesKeyPasswordField(configer.getWechatAesKey());

    // 阿里大于
    MainWindow.mainWindow.setAliServerUrlTextField(configer.getAliServerUrl());
    MainWindow.mainWindow.setAliAppKeyPasswordField(configer.getAliAppKey());
    MainWindow.mainWindow.setAliAppSecretPasswordField(configer.getAliAppSecret());
    MainWindow.mainWindow.setAliSignTextField(configer.getAliSign());

    // MySQL
    MainWindow.mainWindow.setMysqlUrlTextField(configer.getMysqlUrl());
    MainWindow.mainWindow.setMysqlDatabaseTextField(configer.getMysqlDatabase());
    MainWindow.mainWindow.setMysqlUserTextField(configer.getMysqlUser());
    MainWindow.mainWindow.setMysqlPasswordField(configer.getMysqlPassword());

    // 外观
    MainWindow.mainWindow.setSettingThemeComboBox(configer.getTheme());
    MainWindow.mainWindow.setSettingFontNameComboBox(configer.getFont());
    MainWindow.mainWindow.setSettingFontSizeComboBox(configer.getFontSize());

    // 历史消息管理
    String[] headerNames = {"选择", "消息名称"};
    DefaultTableModel model = new DefaultTableModel(null, headerNames);
    MainWindow.mainWindow.getMsgHistable().setModel(model);
    Map<String, String[]> msgMap = msgHisManager.readMsgHis();
    Object[] data;
    for (String msgName : msgMap.keySet()) {
        data = new Object[2];
        data[0] = false;
        data[1] = msgName;
        model.addRow(data);
    }
    MainWindow.mainWindow.getMsgHistable().getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(new JCheckBox()));
    MainWindow.mainWindow.getMsgHistable().getColumnModel().getColumn(0).setCellRenderer(new MyCheckBoxRenderer());
    // 设置列宽
    MainWindow.mainWindow.getMsgHistable().getColumnModel().getColumn(0).setPreferredWidth(50);
    MainWindow.mainWindow.getMsgHistable().getColumnModel().getColumn(0).setMaxWidth(50);

    // 导入历史管理
    String[] headerNames2 = {"选择", "文件名称"};
    DefaultTableModel model2 = new DefaultTableModel(null, headerNames2);
    MainWindow.mainWindow.getImportHisTable().setModel(model2);

    File pushHisDir = new File("data/push_his");
    if (!pushHisDir.exists()) {
        pushHisDir.mkdirs();
    }

    File[] files = pushHisDir.listFiles();
    if (files.length > 0) {
        for (File file : files) {
            data = new Object[2];
            data[0] = false;
            data[1] = file.getName();
            model2.addRow(data);
        }
    }
    MainWindow.mainWindow.getImportHisTable().getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(new JCheckBox()));
    MainWindow.mainWindow.getImportHisTable().getColumnModel().getColumn(0).setCellRenderer(new MyCheckBoxRenderer());
    // 设置列宽
    MainWindow.mainWindow.getImportHisTable().getColumnModel().getColumn(0).setPreferredWidth(50);
    MainWindow.mainWindow.getImportHisTable().getColumnModel().getColumn(0).setMaxWidth(50);
}