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

The following examples show how to use java.io.File#mkdir() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LogsHelper.java    From CommonUtils with Apache License 2.0 6 votes vote down vote up
public static boolean exportLogFiles(@NonNull Context context, @NonNull Intent intent) {
    try {
        File parent = new File(context.getCacheDir(), "logs");
        if (!parent.exists() && !parent.mkdir())
            return false;

        Process process = Runtime.getRuntime().exec("logcat -d");
        File file = new File(parent, "logs-" + System.currentTimeMillis() + ".txt");
        try (FileOutputStream out = new FileOutputStream(file, false)) {
            CommonUtils.copy(process.getInputStream(), out);
        } finally {
            process.destroy();
        }

        Uri uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".logs", file);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        return true;
    } catch (IllegalArgumentException | IOException ex) {
        Log.e(TAG, "Failed exporting logs.", ex);
    }

    return false;
}
 
Example 2
Source File: ChatsAccService.java    From live-chat-engine with Apache License 2.0 6 votes vote down vote up
private void writeFeedback(String accId, ClientInfo info, String text, Date datePreset, ReqInfo reqInfo){
	try {
		
		Date now = datePreset == null? new Date() : datePreset;
		
		File accDir = getAccDir(accId);
		if( ! accDir.exists()) return;
		
		File dayDir = new File(accDir, getLogsDayDirName(now));
		dayDir.mkdir();
		
		String fileName = now.getTime()+"-"+System.nanoTime()+".feed";
		File file = new File(dayDir, fileName);
		
		String ref = reqInfo == null? null : reqInfo.getFinalRef();
		
		FeedbackStore storeData = new FeedbackStore(info, now, text, ref);
		String json = toJson(storeData, true);
		writeFileUTF8(file, json);
		
	}catch (Throwable t) {
		log.error("can't writeFeedback: "+t);
	}
}
 
Example 3
Source File: FileManager.java    From visualee with Apache License 2.0 6 votes vote down vote up
/**
 * Exports Files from the jar to a given directory
 *
 * @param sourceFolder
 * @param fileName
 * @param targetFolder
 */
public static void export(String sourceFolder, String fileName, File targetFolder) {
   if (!targetFolder.exists()) {
      targetFolder.mkdir();
   }
   File dstResourceFolder = new File(targetFolder + sourceFolder + File.separatorChar);
   if (!dstResourceFolder.exists()) {
      dstResourceFolder.mkdir();
   }
   try (InputStream in = FileManager.class.getResourceAsStream(sourceFolder + fileName)) {
      Path out = Paths.get(targetFolder + sourceFolder + fileName);
      Files.copy(in, out, StandardCopyOption.REPLACE_EXISTING);
   } catch (IOException exc) {
      LogProvider.getInstance().error("Can't export " + fileName + " from " + sourceFolder + " (jar) to " + targetFolder, exc);
   }
}
 
Example 4
Source File: SvnWorkspaceProviderImpl.java    From proctor with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a directory with a given suffix and prefix in the parent directory.
 * If the absolute path exists and is not a directory, throws IOException
 * If deleteIfExists is true and directory exists, its contents will be
 * deleted prior to returning.
 * Otherwise, a new directory will be created: throws IOException if fails to create a new directory
 * @param suffix
 * @param parent
 * @param deleteIfExists
 * @return
 */
private static File createWorkspace(final String prefix,
                                    final String suffix,
                                    final File parent,
                                    final boolean deleteIfExists) throws IOException {
    final File dir = getUserDirectory(prefix, suffix, parent);
    if (dir.exists()) {
        if (!dir.isDirectory()) {
            throw new IOException("File " + dir + " exists but is not a directory");
        }
        if (deleteIfExists) {
            FileUtils.cleanDirectory(dir);
        }
    } else {
        if (!dir.mkdir()) {
            throw new IOException("Failed to create directory: " + dir);
        }
    }
    return dir;
}
 
Example 5
Source File: AnsibleOutputListener.java    From tc-ansible-runner with MIT License 6 votes vote down vote up
public AnsibleOutputListener(AgentRunningBuild build, BuildRunnerContext buildRunnerContext, ArtifactsWatcher artifactsWatcher) {
    this.artifactsWatcher = artifactsWatcher;
    this.buildRunnerContext = buildRunnerContext;
    File tmpDir = new File(build.getBuildTempDirectory(), "ansible-run");
    boolean exists = tmpDir.exists(); 
    if (!exists) {
        exists = tmpDir.mkdir();
    }
    if (!exists) {
        LOG.error("Cannot create a directory " + tmpDir.getAbsolutePath() + " for ansible run raw output storage");
        build.getBuildLogger().warning("Cannot create a directory for ansible run raw output storage. Ansible report will not be generated");
    } else {
        String rawFileName = "ansible-run-raw-" + buildRunnerContext.getId() + ".log";
        rawFile = new File(tmpDir, rawFileName);
        try {
            rawFile.createNewFile();
        } catch (IOException e) {
            LOG.error("Cannot create a file " + rawFileName + " for ansible run raw output writing ", e);
            build.getBuildLogger().warning("Cannot create a file for ansible run raw output writing. Ansible report will not be generated");
        }
        build.addSharedConfigParameter(AnsibleRunnerConstants.ARTIFACTS_TMP_DIR_KEY, tmpDir.getAbsolutePath());
    }
}
 
Example 6
Source File: TestSamzaRunner.java    From beam with Apache License 2.0 6 votes vote down vote up
public static SamzaPipelineOptions createSamzaPipelineOptions(PipelineOptions options) {
  try {
    final SamzaPipelineOptions samzaOptions =
        PipelineOptionsValidator.validate(SamzaPipelineOptions.class, options);
    final Map<String, String> config = new HashMap<>(ConfigBuilder.localRunConfig());
    final File storeDir =
        Paths.get(System.getProperty("java.io.tmpdir"), "beam-samza-test").toFile();
    //  Re-create the folder for test stores
    FileUtils.deleteDirectory(storeDir);
    if (!storeDir.mkdir()) {
      // ignore
    }

    config.put(JOB_LOGGED_STORE_BASE_DIR, storeDir.getAbsolutePath());
    config.put(JOB_NON_LOGGED_STORE_BASE_DIR, storeDir.getAbsolutePath());

    if (samzaOptions.getConfigOverride() != null) {
      config.putAll(samzaOptions.getConfigOverride());
    }
    samzaOptions.setConfigOverride(config);
    return samzaOptions;
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 7
Source File: CordovaLibraryJsContainerInitializer.java    From thym with Eclipse Public License 1.0 5 votes vote down vote up
private IPath getLibraryRuntimeFolder(){
	IPath libraryRuntimePath = Platform.getStateLocation(Platform.getBundle(HybridCore.PLUGIN_ID)).append("cordovaJsLib");
	File libRuntimeFile = libraryRuntimePath.toFile();
	if(!libRuntimeFile.isDirectory()){
		libRuntimeFile.mkdir();
	}
	return libraryRuntimePath;

}
 
Example 8
Source File: ScreenshotComposer.java    From Panoramic-Screenshot with GNU General Public License v3.0 5 votes vote down vote up
public void setOutputDir(String opt) {
	mOutDir = opt;
	
	File out = new File(mOutDir);
	if (!out.exists()) {
		out.mkdirs();
		out.mkdir();
	}
}
 
Example 9
Source File: MynlpBuilder.java    From mynlp with Apache License 2.0 5 votes vote down vote up
private File ensureDir(File file) throws IOException {
    if (!file.exists()) {
        createParentDirs(file);
        file.mkdir();
    }
    if (!file.isDirectory()) {
        throw new IOException(file + " is not dir");
    }
    return file;
}
 
Example 10
Source File: FileUtils.java    From wakao-app with MIT License 5 votes vote down vote up
/**
 * 创建目录
 * 
 * @param path
 */
public static PathStatus createPath(String newPath) {
	File path = new File(newPath);
	if (path.exists()) {
		return PathStatus.EXITS;
	}
	if (path.mkdir()) {
		return PathStatus.SUCCESS;
	} else {
		return PathStatus.ERROR;
	}
}
 
Example 11
Source File: LocalFilesystem.java    From reader with MIT License 5 votes vote down vote up
/**
 * Copy a directory
 *
 * @param srcDir directory to be copied
 * @param destinationDir destination to be copied to
 * @return a DirectoryEntry object
 * @throws JSONException
 * @throws IOException
 * @throws NoModificationAllowedException
 * @throws InvalidModificationException
 */
private JSONObject copyDirectory(File srcDir, File destinationDir) throws JSONException, IOException, NoModificationAllowedException, InvalidModificationException {
    // Renaming a file to an existing directory should fail
    if (destinationDir.exists() && destinationDir.isFile()) {
        throw new InvalidModificationException("Can't rename a file to a directory");
    }

    // Check to make sure we are not copying the directory into itself
    if (isCopyOnItself(srcDir.getAbsolutePath(), destinationDir.getAbsolutePath())) {
        throw new InvalidModificationException("Can't copy itself into itself");
    }

    // See if the destination directory exists. If not create it.
    if (!destinationDir.exists()) {
        if (!destinationDir.mkdir()) {
            // If we can't create the directory then fail
            throw new NoModificationAllowedException("Couldn't create the destination directory");
        }
    }
    

    for (File file : srcDir.listFiles()) {
        File destination = new File(destinationDir.getAbsoluteFile() + File.separator + file.getName());
        if (file.isDirectory()) {
            copyDirectory(file, destination);
        } else {
            copyFile(file, destination);
        }
    }

    return makeEntryForFile(destinationDir);
}
 
Example 12
Source File: Presenter.java    From ttt with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private BufferedOutputStream getFrameResourceStream(URI uri, FrameResource r, File[] retResourceFile) throws IOException {
    File d = getOutputDirectoryRetained(uri);
    if (!d.exists()) {
        if (!d.mkdir())
            return null;
    }
    if (d.exists()) {
        String resourceFileName = r.getName();
        File resourceFile = new File(d, resourceFileName).getCanonicalFile();
        if (retResourceFile != null)
            retResourceFile[0] = resourceFile;
        return new BufferedOutputStream(new FileOutputStream(resourceFile));
    } else
        return null;
}
 
Example 13
Source File: StoreUtils.java    From letv with Apache License 2.0 5 votes vote down vote up
public static long getAvailableSpaceByPath(String path) {
    StatFs statFs;
    Exception e;
    if (TextUtils.isEmpty(path)) {
        return -1;
    }
    File dir = new File(path);
    if (!dir.exists()) {
        dir.mkdir();
    }
    long block = 0;
    long size = 0;
    try {
        StatFs statFs2 = new StatFs(path);
        try {
            block = (long) statFs2.getAvailableBlocks();
            size = (long) statFs2.getBlockSize();
            statFs = statFs2;
        } catch (Exception e2) {
            e = e2;
            statFs = statFs2;
            e.printStackTrace();
            return size * block;
        }
    } catch (Exception e3) {
        e = e3;
        e.printStackTrace();
        return size * block;
    }
    return size * block;
}
 
Example 14
Source File: SubmarineServer.java    From submarine with Apache License 2.0 5 votes vote down vote up
private static WebAppContext setupWebAppContext(HandlerList handlers,
    SubmarineConfiguration conf) {
  WebAppContext webApp = new WebAppContext();
  webApp.setContextPath("/");
  File warPath = new File(conf.getString(SubmarineConfVars.ConfVars.WORKBENCH_WEB_WAR));
  LOG.info("workbench web war file path is {}.",
      conf.getString(SubmarineConfVars.ConfVars.WORKBENCH_WEB_WAR));
  if (warPath.isDirectory()) {
    // Development mode, read from FS
    webApp.setResourceBase(warPath.getPath());
    webApp.setParentLoaderPriority(true);
  } else {
    // use packaged WAR
    webApp.setWar(warPath.getAbsolutePath());
    File warTempDirectory = new File("webapps");
    warTempDirectory.mkdir();
    webApp.setTempDirectory(warTempDirectory);
  }

  webApp.addServlet(new ServletHolder(new DefaultServlet()), "/");
  // When requesting the workbench page, the content of index.html needs to be returned,
  // otherwise a 404 error will be displayed
  // NOTE: If you modify the workbench directory in the front-end URL,
  // you need to modify the `/workbench/*` here.
  webApp.addServlet(new ServletHolder(RefreshServlet.class), "/user/*");
  webApp.addServlet(new ServletHolder(RefreshServlet.class), "/workbench/*");

  handlers.setHandlers(new Handler[] { webApp });

  return webApp;
}
 
Example 15
Source File: ShellFolderMemoryLeak.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void createTestData(String testDirectory) {
    String folder = "folder_";
    File testFolder = new File(testDirectory);
    if (testFolder.exists()) {
        clearTestData(testDirectory);
    } else {
        if (testFolder.mkdir()) {
            for (int inx = 0; inx < 100; inx++) {
                new File(testFolder + File.separator + folder + inx).mkdir();
            }
        } else {
            throw new RuntimeException("Failed to create testDirectory");
        }
    }
}
 
Example 16
Source File: Filenames.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the distribution file, creating its directory if needed.
 *
 * @param  rootDirectory  the project root directory.
 * @param  filename       name of the file to create.
 */
static File distributionFile(final String rootDirectory, final String filename) throws MojoExecutionException {
    final File outDirectory = new File(new File(rootDirectory, TARGET_DIRECTORY), DISTRIBUTION_DIRECTORY);
    if (!outDirectory.isDirectory()) {
        if (!outDirectory.mkdir()) {
            throw new MojoExecutionException("Can't create the \"" + DISTRIBUTION_DIRECTORY + "\" directory.");
        }
    }
    return new File(outDirectory, filename);
}
 
Example 17
Source File: TestSpoolDirSource.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Test
public void testRecoverableDataParserError() throws Exception {
  File f = new File("target", UUID.randomUUID().toString());
  f.mkdir();

  SpoolDirConfigBean conf = new SpoolDirConfigBean();
  conf.dataFormat = DataFormat.DELIMITED;
  conf.spoolDir = f.getAbsolutePath();
  conf.batchSize = 10;
  conf.overrunLimit = 100;
  conf.poolingTimeoutSecs = 10;
  conf.filePattern = "file-[0-9].log";
  conf.pathMatcherMode = PathMatcherMode.GLOB;
  conf.maxSpoolFiles = 10;
  conf.initialFileToProcess = "file-0.log";
  conf.dataFormatConfig.compression = Compression.NONE;
  conf.dataFormatConfig.filePatternInArchive = "*";
  conf.dataFormatConfig.csvHeader = CsvHeader.WITH_HEADER;
  conf.errorArchiveDir = null;
  conf.postProcessing = PostProcessingOptions.NONE;
  conf.retentionTimeMins = 10;
  conf.allowLateDirectory = false;
  conf.dataFormatConfig.textMaxLineLen = 10;
  conf.dataFormatConfig.onParseError = OnParseError.ERROR;
  conf.dataFormatConfig.maxStackTraceLines = 0;

  FileOutputStream outputStream = new FileOutputStream(new File(conf.spoolDir, "file-0.log"));
  IOUtils.writeLines(ImmutableList.of("A,B", "a,b,c", "a,b"), "\n", outputStream);
  outputStream.close();

  SpoolDirSource source = new SpoolDirSource(conf);
  PushSourceRunner runner = new PushSourceRunner.Builder(SpoolDirDSource.class, source)
    .setOnRecordError(OnRecordError.TO_ERROR)
    .addOutputLane("lane")
    .build();
  final List<Record> records = Collections.synchronizedList(new ArrayList<>(10));

  runner.runInit();
  try {
    runner.runProduce(new HashMap<>(), 10, output -> {
      synchronized (records) {
        records.addAll(output.getRecords().get("lane"));
      }
      runner.setStop();
    });

    runner.waitOnProduce();

    // Verify proper record
    Assert.assertNotNull(records);
    Assert.assertEquals(1, records.size());

    // And error record
    List<Record> errorRecords = runner.getErrorRecords();
    Assert.assertEquals(1, errorRecords.size());

  } finally {
    source.destroy();
    runner.runDestroy();
  }
}
 
Example 18
Source File: ExpUai06Small.java    From blip with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void learn() throws Exception {
    int n = 1000000;

    String r = f("%s/%s/", path, net);
    File dir = new File(r);

    if (!new File(r).exists()) {
        dir.mkdir();
    }

    BayesianNetwork orig = BnErgReader.ex(r + net + ".erg");
    // BnUaiWriter.ex(r+net, orig);
    String d = r + "dat";

    if (!(new File(d).exists())) {
        SamGe.ex(orig, d, n);
    }

    DataSet dat = getDataSet(d);

    if (!(new File(r + "new.net").exists())) {
        parle(dat, r + "new", orig);
    }

    String s = r + "jkl";

    if (!(new File(s).exists())) {
        IndependenceScorer is = new IndependenceScorer();

        is.ph_scores = s;
        is.max_exec_time = 5;
        is.scoreNm = "bdeu";
        is.alpha = 1;
        is.max_pset_size = 5;
        is.thread_pool_size = 1;
        is.go(dat);
    }

    for (int l : new int[] { 0, 1, 2, 3, 4, 5}) {
        String best = r + "best" + l;

        if (!(new File(best).exists())) {
            AsobsSolver aso = new AsobsSolver();

            aso.max_exec_time = learning / 10;
            aso.thread_pool_size = 1;
            aso.init(getScoreReader(s, l));
            aso.go(best);
        }
        BayesianNetwork BnBest = BnResReader.ex(best);

        parle(dat, best, BnBest);
    }

}
 
Example 19
Source File: UpdateManager.java    From qingyang with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {

	try {

		String apkName = mUpdate.getVersionName() + ".apk";

		String tmpName = mUpdate.getVersionName() + ".tmp";

		// 判断是否挂载了SD卡
		String storageState = Environment.getExternalStorageState();

		if (storageState.equals(Environment.MEDIA_MOUNTED)) {
			savePath = Environment.getExternalStorageDirectory()
					.getAbsolutePath() + "/qingyang/Update";
			File file = new File(savePath);
			if (!file.exists()) {
				file.mkdir();
			}

			apkFilePath = savePath + "/" + apkName;

			tempFilePath = savePath + "/" + tmpName;
		}

		if (apkFilePath == null || apkFilePath.equals("")) {
			mHandler.sendEmptyMessage(DOWN_NOSDCARD);
			return;
		}

		File apkFile = new File(apkFilePath);

		// 如果已经存在更新文件
		if (apkFile.exists()) {
			downloadDialog.dismiss();
			downloadDialog = null;
			installApk();
			return;
		}

		File tmpFile = new File(tempFilePath);

		FileOutputStream fos = new FileOutputStream(tmpFile);

		URL url = new URL(apkUrl);

		HttpURLConnection conn = (HttpURLConnection) url
				.openConnection();

		conn.connect();

		int length = conn.getContentLength();

		InputStream is = conn.getInputStream();

		DecimalFormat df = new DecimalFormat("0.00");

		apkFileSize = df.format((float) length / 1024 / 1024) + "MB";

		int count = 0;

		byte buf[] = new byte[1024];

		do {
			int numread = is.read(buf);

			count += numread;
			// 当先下载文件大小
			tmpFileSize = df.format((float) count / 1024 / 1024) + "MB";

			// 当前进度值
			progress = (int) (((float) count / length) * 100);

			// 更新进度
			mHandler.sendEmptyMessage(DOWN_UPDATE);

			if (numread <= 0) {
				// 下载完成-奖临时下载文件装成APK文件
				if (tmpFile.renameTo(apkFile)) {
					// 通知安装
					mHandler.sendEmptyMessage(DOWN_OVER);
				}
				break;
			}
			fos.write(buf, 0, numread);
		} while (!interceptFlag);// 点击取消就停止下载

		fos.close();
		is.close();
	} catch (Exception e) {
		e.printStackTrace();
	}

}
 
Example 20
Source File: DFlowFMHistoryFileTest.java    From OpenDA with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void testWaterlevelHistories() throws Exception {
//		System.out.println("==============================================================================");
//		System.out.println(" Test for reading timeseries from *_his.nc and export to *.noos.");
//		System.out.println("==============================================================================");

        // specify which variable to export
		String Outputvar = "sea_surface_height";
        File inputDir = new File(testData.getTestRunDataDir(), "Historyfile");
		File outputDir = new File(inputDir, "noos_output");
		if(!outputDir.exists()){
			if (!outputDir.mkdir()) {
				throw new RuntimeException("Problem creating directory"+outputDir);
			}

		}else{
			throw new RuntimeException("Output directory already exists. This should not be possible");
		}

        String fileName="simple_waal_his.nc";
		IDataObject hisfile = new NetcdfDataObject();
		hisfile.initialize(inputDir, new String[]{fileName,"true","false"}); //The first option 'true' is crucial to get timeseries!

		String[] exchangeItemIDs = hisfile.getExchangeItemIDs();

//		for (String id : exchangeItemIDs) {
//			// find exchangeItem to export to NOOS format
//			if (id.matches(Outputvar)) {
//				IExchangeItem ex = hisfile.getDataObjectExchangeItem(id);
//				// get time
//				double[] timevals = ex.getTimes();
//				// get values
//				Array vals = (Array) ex.getValues();
//				int[] dims = vals.getDimensions();
//				double[] vec = new double[dims[0]];
//				int idx = 0;
//				while (idx < dims[1]) {
//					// this presumes that values are stored as (time,station) in the his-file
//					for (int i = 0; i < dims[0] ; i++) {
//						vec[i] = vals.getValueAsDouble(idx+i*dims[1]);
//					}
//					// create a timeserie for this slice
//					TimeSeries series = new TimeSeries(timevals,vec);
//					series.setLocation("station" + idx);
//					series.setQuantity(Outputvar);
//					series.setSource("twin experiment DFlowFM");
//					// create NoosDataObject, add the new timeseries to it and write to file.
//					NoosDataObject noos = new NoosDataObject();
//					noos.initialize(outputDir,new String[]{""});
//					noos.addExchangeItem(series);
//					noos.finish();
//
//					idx++;
//				}
//			}
//		}
		IExchangeItem obs1 = hisfile.getDataObjectExchangeItem("Obs01.waterlevel");
		//System.out.println("obs1="+obs1.toString());
		String id1=obs1.getId();
		assertEquals("Obs01.waterlevel", id1);
		double[] times1=obs1.getTimes();
		assertEquals(2881, times1.length);
		assertEquals(48865.0,times1[0],0.001);
		assertEquals(48875.0,times1[2880],0.001);
		double[] values1=obs1.getValuesAsDoubles();
		assertEquals(2881, values1.length);
		assertEquals(0.0,values1[0],0.001);
		assertEquals(1.013,values1[2880],0.001);

		IExchangeItem obs3 = hisfile.getDataObjectExchangeItem("Obs03.waterlevel");
		//System.out.println("obs3="+obs3.toString());
		String id3=obs3.getId();
		assertEquals("Obs03.waterlevel", id3);
		double[] times3=obs3.getTimes();
		assertEquals(2881, times3.length);
		assertEquals(48865.0,times3[0],0.001);
		assertEquals(48875.0,times3[2880],0.001);
		double[] values3=obs3.getValuesAsDoubles();
		assertEquals(2881, values3.length);
		assertEquals(0.0,values3[0],0.001);
		assertEquals(0.999,values3[2880],0.001);
    }