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

The following are Jave code examples for showing how to use mkdir() 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: EARLGREY   File: Kernel.java   View Source Code Vote up 7 votes
public boolean checkFileSystem() {
	// CHEQUEAMOS Y CREAMOS LAS CARPETAS
	this.log.Info("Verificando sistema de archivos");
	File geos = new File("kernel");
	File logs = new File("kernel/logs");
	File properties = new File("kernel/properties");
	File backups = new File("kernel/backups");
	File model = new File("kernel/model");
	File controller = new File("kernel/controller");
	File policies = new File("kernel/policies");
	//CHEQUEAMOS
	boolean status = true;
	if(!geos.exists()) status = geos.mkdir();
	if(status && !logs.exists()) status = logs.mkdir(); 
	if(status && !properties.exists()) status = properties.mkdir(); 
	if(status && !backups.exists()) status = backups.mkdir(); 
	if(status && !model.exists()) status = model.mkdir(); 
	if(status && !controller.exists()) status = controller.mkdir();
	if(status && !policies.exists()) status = policies.mkdir();
	return status;
}
 
Example 2
Project: monarch   File: InterruptDiskJUnitTest.java   View Source Code Vote up 7 votes
@Before
public void setUp() {
  Properties props = new Properties();
  props.setProperty(MCAST_PORT, "0");
  props.setProperty(LOCATORS, "");
  props.setProperty(LOG_LEVEL, "config"); // to keep diskPerf logs smaller
  props.setProperty(STATISTIC_SAMPLING_ENABLED, "true");
  props.setProperty(ENABLE_TIME_STATISTICS, "true");
  props.setProperty(STATISTIC_ARCHIVE_FILE, "stats.gfs");
  ds = DistributedSystem.connect(props);
  cache = CacheFactory.create(ds);
  File diskStore = new File("diskStore");
  diskStore.mkdir();
  cache.createDiskStoreFactory().setMaxOplogSize(1).setDiskDirs(new File[] {diskStore})
      .create("store");
  region = cache.createRegionFactory(RegionShortcut.REPLICATE_PERSISTENT)
      .setDiskStoreName("store").create("region");
  ex = Executors.newSingleThreadExecutor();
}
 
Example 3
Project: GxIconAndroid   File: ExtraUtil.java   View Source Code Vote up 7 votes
public static String getDeviceId(Context context) {
    String androidId = Settings.Secure.getString(context.getContentResolver(),
            Settings.Secure.ANDROID_ID);
    if (!TextUtils.isEmpty(androidId)) {
        String serial = Build.SERIAL;
        if (!"unknown".equalsIgnoreCase(serial)) {
            return androidId + serial;
        }
        return androidId;
    }

    File file = new File(context.getFilesDir(), "deviceId");
    file.mkdir();
    File[] files = file.listFiles();
    if (files.length > 0) {
        return files[0].getName();
    }
    String id = UUID.randomUUID().toString();
    (new File(file, id)).mkdir();
    return id;
}
 
Example 4
Project: wcs-android-sdk   File: MainActivity.java   View Source Code Vote up 7 votes
public File getSDFileDir() {
	File sdDir = null;
	boolean sdCardExist = Environment.getExternalStorageState()
			.equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在
	if (!sdCardExist) {
		return null;
	}
	sdDir = Environment.getExternalStorageDirectory();//获取跟目录
	File dir = new File(sdDir + File.separator + "WcsSdk");
	if (!dir.exists()) {
		dir.mkdir();
	}
	if (mFilePath == null) {
		mFilePath = dir.toString();
	}
	return dir;
}
 
Example 5
Project: Quavo   File: SequenceTypeList.java   View Source Code Vote up 7 votes
@Override
public void print() {
	File dir = new File(Constants.TYPE_PATH);

	if (!dir.exists()) {
		dir.mkdir();
	}

	File file = new File(Constants.TYPE_PATH, "sequences.txt");
	try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
		Arrays.stream(seqs).filter(Objects::nonNull).forEach((SequenceType t) -> {
			TypePrinter.print(t, writer);
		});
		writer.flush();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 6
Project: joai-project   File: XMLConversionService.java   View Source Code Vote up 6 votes
/**
 *  Factory for use in Servlets to create an XMLConversionService using
 *  configurations found in the Servlet context parameters. This method also
 *  places the path to the XSL files directory in the servlet context under
 *  'xslFilesDirecoryPath', for use by the JavaXmlConverters. <p>
 *
 *  To configure a format converter that uses an XSL style sheet or Java class,
 *  the context param-name must begin with the either 'xslconverter' or
 *  'javaconverter' and must be unique. The param-value must be of the form
 *  'xslfile.xsl|[from format]\[to format]' or '[fully qualified Java
 *  class]|[from format]\[to format]'.
 *
 * @param  servletContext      The ServletContext
 * @param  xslFilesDirecory    The base directory where the XSL files are
 *      located
 * @param  xmlCachDirecory     The directory where the service will cache the
 *      converted XML files
 * @param  filterDeclarations  Set to true to filter out the XML and DTD
 *      declarations in the converted XML
 * @return                     The XMLConversionService
 * @exception  Exception       If error
 */
public static XMLConversionService xmlConversionServiceFactoryForServlets(
                                                                          ServletContext servletContext,
                                                                          File xslFilesDirecory,
                                                                          File xmlCachDirecory,
                                                                          boolean filterDeclarations)
	 throws Exception {

	// Set up an XML Conversion Service:

	// Place the xsl dir path in the Servlet context for use by the JavaXmlConverters
	servletContext.setAttribute("xslFilesDirecoryPath", xslFilesDirecory.getAbsolutePath());
	XMLConversionService xmlConversionService = null;
	xmlCachDirecory.mkdir();

	xmlConversionService =
		new XMLConversionService(xmlCachDirecory, filterDeclarations);

	// Add configured converters:
	Enumeration enumeration = servletContext.getInitParameterNames();
	String param;
	while (enumeration.hasMoreElements()) {
		param = (String) enumeration.nextElement();
		if (param.toLowerCase().startsWith("xslconverter")) {
			xmlConversionService.addXslConverterHelper(servletContext.getInitParameter(param), xslFilesDirecory);
		}
		if (param.toLowerCase().startsWith("javaconverter")) {
			xmlConversionService.addJavaConverterHelper(servletContext.getInitParameter(param), servletContext);
		}
	}
	return xmlConversionService;
}
 
Example 7
Project: monarch   File: IndexCreationJUnitTest.java   View Source Code Vote up 6 votes
@Test
public void testIndexCreationFromXMLForLocalScope() throws Exception {
  InternalDistributedSystem.getAnyInstance().disconnect();
  File file = new File("persistData0");
  file.mkdir();

  Properties props = new Properties();
  props.setProperty(NAME, "test");
  props.setProperty(MCAST_PORT, "0");
  props.setProperty(CACHE_XML_FILE,
      getClass().getResource("index-creation-without-eviction.xml").toURI().getPath());
  DistributedSystem ds = DistributedSystem.connect(props);
  Cache cache = CacheFactory.create(ds);
  Region localRegion = cache.getRegion("localRegion");
  for (int i = 0; i < 100; i++) {
    Portfolio pf = new Portfolio(i);
    localRegion.put("" + i, pf);
  }
  QueryService qs = cache.getQueryService();
  Index ind = qs.getIndex(localRegion, "localIndex");
  assertNotNull("Index localIndex should have been created ", ind);
  // verify that a query on the creation time works as expected
  SelectResults results = (SelectResults) qs
      .newQuery("<trace>SELECT * FROM " + localRegion.getFullPath() + " Where ID > 0").execute();
  assertEquals("OQL index results did not match", 99, results.size());
  ds.disconnect();
  FileUtil.delete(file);
}
 
Example 8
Project: bluetooth-manager-tinyb   File: NativesLoader.java   View Source Code Vote up 6 votes
private static File createTempDirectory() throws IOException {
    File tempDirectory = File.createTempFile("tinyb", "libs");
    tempDirectory.delete();
    tempDirectory.mkdir();
    try {
        tempDirectory.deleteOnExit();
    } catch (Exception ignored) {
        // old jvms
    }
    return tempDirectory;
}
 
Example 9
Project: FireFiles   File: RawDocumentFile.java   View Source Code Vote up 6 votes
@Override
public DocumentFile createDirectory(String displayName) {
    final File target = new File(mFile, displayName);
    if (target.isDirectory() || target.mkdir()) {
        return new RawDocumentFile(this, target);
    } else {
        return null;
    }
}
 
Example 10
Project: NavyCraft2-Lite   File: XMLHandler.java   View Source Code Vote up 6 votes
public static void load() {
	File dir = NavyCraft.instance.getDataFolder();
	if (!dir.exists())
		dir.mkdir();
	
	File config = new File(NavyCraft.instance.getDataFolder(), NavyCraft.instance.configFile.filename);
	if (!config.exists()) {
		return;
	}
	Document doc = null;
	try {
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		doc = dBuilder.parse(config.toURI().getPath());
		doc.getDocumentElement().normalize();
		
		NodeList list;
		
		for(Object configLine : NavyCraft.instance.configFile.ConfigSettings.keySet().toArray()) {
			String configKey = (String) configLine;

			list = doc.getElementsByTagName(configKey);
			
			try {
				String value = list.item(0).getChildNodes().item(0).getNodeValue();
				NavyCraft.instance.configFile.ConfigSettings.put(configKey, value);
			} catch (Exception ex){

			}
		}
	}
	catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 11
Project: TOSCAna   File: ServiceTest.java   View Source Code Vote up 6 votes
private void setUpMyApp() throws IOException, JSONException {
    NodeVisitors visitor = new NodeVisitors(myApp);
    EffectiveModel lamp = new EffectiveModel(TestCsars.VALID_LAMP_NO_INPUT_TEMPLATE, log);
    ArrayList<String> paths = new ArrayList<>();
    String resourcesPath = "src/test/resources/";
    File sourceDir = new File(resourcesPath + "csars/yaml/valid/lamp-noinput/");
    targetDir = new File(tmpdir, "targetDir");
    sourceDir.mkdir();
    targetDir.mkdir();
    PluginFileAccess fileAccess = new PluginFileAccess(sourceDir, targetDir, log);
    Set<RootNode> nodes = lamp.getNodes();

    paths.add("my_app/myphpapp.php");
    paths.add("my_app/mysql-credentials.php");
    paths.add("my_app/create_myphpapp.sh");
    paths.add("my_app/configure_myphpapp.sh");
    paths.add("my_db/createtable.sql");

    for (VisitableNode node : nodes) {
        node.accept(visitor);
    }
    myApp = visitor.getFilledApp();
    assumeNotNull(connection);
    myApp.setConnection(connection);
    myApp.setProvider(provider);
    String pathToApplication = myApp.getPathToApplication();
    myApp.setPathToApplication(targetDir + "/" + pathToApplication + "/");
    FileCreator fileCreator = new FileCreator(fileAccess, myApp);
    fileCreator.createFiles();
}
 
Example 12
Project: tqdev-metrics   File: PrometheusFileReporter.java   View Source Code Vote up 6 votes
/**
 * Report.
 *
 * @return true, if successful
 */
@Override
public boolean report() {
	if (!registry.isEnabled()) {
		return true;
	}
	File dir = new File(metricPath);
	if (!dir.exists()) {
		if (!dir.mkdir()) {
			return false;
		}
	}
	DateFormat formatter = new SimpleDateFormat(dateFormat);
	String filename = metricPath + "/" + formatter.format(new Date(registry.getMillis())) + ".prom";
	try {
		FileOutputStream fos = new FileOutputStream(filename, true);
		BufferedOutputStream out = new BufferedOutputStream(fos, 8192);
		write(out);
		out.close();
		compress(filename);
		remove(maxFileCount);
	} catch (IOException e) {
		// TODO: log
		return false;
	}
	return true;
}
 
Example 13
Project: scanning   File: MockFilePathService.java   View Source Code Vote up 6 votes
@Override
public String createFolderForLinkedFiles(String filename) throws Exception {
	String bareFilename = getBareFilename(filename);
	File newDir = new File(dir, bareFilename);
	newDir.mkdir();

	return newDir.toString();
}
 
Example 14
Project: android_nextgis_mobile   File: FileUtil.java   View Source Code Vote up 6 votes
public static boolean copyRecursive(
        File from,
        File to)
{
    if (from.isDirectory()) {
        if (!to.exists()) {
            if (!to.mkdir()) {
                return false;
            }
        }

        for (String path : from.list()) {
            if (!copyRecursive(new File(from, path), new File(to, path))) {
                return false;
            }
        }
    } else {

        try {
            InputStream in = new FileInputStream(from);
            OutputStream out = new FileOutputStream(to);
            byte[] buf = new byte[ConstantsUI.IO_BUFFER_SIZE];
            copyStream(in, out, buf, ConstantsUI.IO_BUFFER_SIZE);
            in.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    return true;
}
 
Example 15
Project: monarch   File: DiskStoreCommandsDUnitTest.java   View Source Code Vote up 5 votes
@Test
public void testescribeOfflineDiskStore() {
  setUpJmxManagerOnVm0ThenConnect(null);

  final File diskStoreDir =
      new File(new File(".").getAbsolutePath(), "DiskStoreCommandDUnitDiskStores");
  diskStoreDir.mkdir();
  this.filesToBeDeleted.add(diskStoreDir.getAbsolutePath());

  final String diskStoreName1 = "DiskStore1";
  final String region1 = "Region1";
  final String region2 = "Region2";

  final VM vm1 = Host.getHost(0).getVM(1);
  vm1.invoke(new SerializableRunnable() {
    public void run() {
      final Cache cache = getCache();

      DiskStoreFactory diskStoreFactory = cache.createDiskStoreFactory();
      diskStoreFactory.setDiskDirs(new File[] {diskStoreDir});
      final DiskStore diskStore1 = diskStoreFactory.create(diskStoreName1);
      assertNotNull(diskStore1);

      RegionFactory regionFactory =
          cache.createRegionFactory(RegionShortcut.REPLICATE_PERSISTENT);
      regionFactory.setDiskStoreName(diskStoreName1);
      regionFactory.setDiskSynchronous(true);
      regionFactory.create(region1);

      regionFactory.setCompressor(SnappyCompressor.getDefaultInstance());
      regionFactory.create(region2);

      cache.close();
      assertTrue(new File(diskStoreDir, "BACKUP" + diskStoreName1 + ".if").exists());
    }
  });

  CommandResult cmdResult = executeCommand("describe offline-disk-store --name=" + diskStoreName1
      + " --disk-dirs=" + diskStoreDir.getAbsolutePath());
  assertEquals(Result.Status.OK, cmdResult.getStatus());
  String stringResult = commandResultToString(cmdResult);
  assertEquals(3, countLinesInString(stringResult, false));
  assertTrue(stringContainsLine(stringResult, ".*/" + region1
      + ": -lru=none -concurrencyLevel=16 -initialCapacity=16 -loadFactor=0.75 -offHeap=false -compressor=none -statisticsEnabled=false -customAttrributes=null -regionMapFactory="));
  assertTrue(stringContainsLine(stringResult, ".*/" + region2
      + ": -lru=none -concurrencyLevel=16 -initialCapacity=16 -loadFactor=0.75 -offHeap=false -compressor=org.apache.geode.compression.SnappyCompressor -statisticsEnabled=false -customAttrributes=null -regionMapFactory="));

  cmdResult = executeCommand("describe offline-disk-store --name=" + diskStoreName1
      + " --disk-dirs=" + diskStoreDir.getAbsolutePath() + " --region=/" + region1);
  stringResult = commandResultToString(cmdResult);
  assertEquals(2, countLinesInString(stringResult, false));
  assertTrue(stringContainsLine(stringResult, ".*/" + region1 + ": .*"));
  assertFalse(stringContainsLine(stringResult, ".*/" + region2 + ": .*"));
}
 
Example 16
Project: jdk8u-jdk   File: bug7036025.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws Exception {
    String systemLookAndFeelClassName = UIManager.getSystemLookAndFeelClassName();

    if (!systemLookAndFeelClassName.toLowerCase().contains("windows")) {
        System.out.println("The test is only for Windows OS.");

        return;
    }

    File file = new File(DIR);

    if (!file.exists()) {
        if (!file.mkdir()) {
            throw new RuntimeException("Cannot create " + DIR);
        }

        file.deleteOnExit();
    }

    UIManager.setLookAndFeel(systemLookAndFeelClassName);

    new JFileChooser(file);

    System.out.println("Test passed for LookAndFeel " + UIManager.getLookAndFeel().getName());
}
 
Example 17
Project: verify-hub   File: ConfigAppRule.java   View Source Code Vote up 5 votes
private void createFedConfig() {
    FED_CONFIG_ROOT.mkdir();
    try {
        FileUtils.cleanDirectory(FED_CONFIG_ROOT);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    File countryFolder = new File(FED_CONFIG_ROOT, "countries");
    File idpFolder = new File(FED_CONFIG_ROOT, "idps");
    File matchingServiceFolder = new File(FED_CONFIG_ROOT, "matching-services");
    File transactionFolder = new File(FED_CONFIG_ROOT, "transactions");

    countryFolder.mkdir();
    idpFolder.mkdir();
    matchingServiceFolder.mkdir();
    transactionFolder.mkdir();

    if (transactions.isEmpty()) {
        transactions.add(
            aTransactionConfigData()
                .withEntityId("default-rp-entity-id")
                .withMatchingServiceEntityId("default-rp-msa-entity-id")
                .build()
        );
    }
    if (matchingServices.isEmpty()) {
        matchingServices.add(
            aMatchingServiceConfigEntityData().withEntityId("default-rp-msa-entity-id").build()
        );
    }
    if (idps.isEmpty()) {
        idps.add(
            anIdentityProviderConfigData()
                .withEntityId("default-idp-entity-id")
                .withOnboarding(asList("default-rp-entity-id"))
                .build()
        );
    }
    if (countries.isEmpty()) {
        countries.add(
            aCountriesConfigEntityData()
                .withEntityId("default-country-entity-id")
                .withSimpleId("default-country-simple-id")
                .build()
        );
    }

    IntStream.range(0, transactions.size()).forEach(i -> writeFile(transactionFolder, i, transactions.get(i)));
    IntStream.range(0, matchingServices.size()).forEach(i -> writeFile(matchingServiceFolder, i, matchingServices.get(i)));
    IntStream.range(0, idps.size()).forEach(i -> writeFile(idpFolder, i, idps.get(i)));
    IntStream.range(0, countries.size()).forEach(i -> writeFile(countryFolder, i, countries.get(i)));
}
 
Example 18
Project: alerta-fraude   File: LocalFilesystem.java   View Source Code Vote up 5 votes
private void copyDirectory(Filesystem srcFs, LocalFilesystemURL srcURL, File dstDir, boolean move) throws IOException, NoModificationAllowedException, InvalidModificationException, FileExistsException {
    if (move) {
        String realSrcPath = srcFs.filesystemPathForURL(srcURL);
        if (realSrcPath != null) {
            File srcDir = new File(realSrcPath);
            // If the destination directory already exists and is empty then delete it.  This is according to spec.
            if (dstDir.exists()) {
                if (dstDir.list().length > 0) {
                    throw new InvalidModificationException("directory is not empty");
                }
                dstDir.delete();
            }
            // Try to rename the directory
            if (srcDir.renameTo(dstDir)) {
                return;
            }
            // Trying to rename the file failed.  Possibly because we moved across file system on the device.
        }
    }

    if (dstDir.exists()) {
        if (dstDir.list().length > 0) {
            throw new InvalidModificationException("directory is not empty");
        }
    } else {
        if (!dstDir.mkdir()) {
            // If we can't create the directory then fail
            throw new NoModificationAllowedException("Couldn't create the destination directory");
        }
    }

    LocalFilesystemURL[] children = srcFs.listChildren(srcURL);
    for (LocalFilesystemURL childLocalUrl : children) {
        File target = new File(dstDir, new File(childLocalUrl.path).getName());
        if (childLocalUrl.isDirectory) {
            copyDirectory(srcFs, childLocalUrl, target, false);
        } else {
            copyFile(srcFs, childLocalUrl, target, false);
        }
    }

    if (move) {
        srcFs.recursiveRemoveFileAtLocalURL(srcURL);
    }
}
 
Example 19
Project: openjdk-jdk10   File: Arrrghs.java   View Source Code Vote up 5 votes
private void initEmptyDir(File emptyDir) throws IOException {
    if (emptyDir.exists()) {
        recursiveDelete(emptyDir);
    }
    emptyDir.mkdir();
}
 
Example 20
Project: googles-monorepo-demo   File: FileTreeTraverserTest.java   View Source Code Vote up 5 votes
private File newDir(String name) throws IOException {
  File file = new File(dir, name);
  file.mkdir();
  return file;
}