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

The following examples show how to use java.io.File#createNewFile() . 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: FileReaderAndWriter.java    From AMC with Apache License 2.0 6 votes vote down vote up
/**
 * Write the content to the file. If the file does not exist, create it
 * first.
 * 
 * @param filePath
 * @param content
 * @throws IOException
 */
public static void writeFile(String filePath, String content) {
	filePath = OSFilePathConvertor.convertOSFilePath(filePath);
	try {
		File aFile = new File(filePath);
		// Create parent directory.
		// Attention: if the file path contains "..", mkdirs() does not
		// work!
		File parent = aFile.getParentFile();
		parent.mkdirs();
		
		if (!aFile.exists()) {
			aFile.createNewFile();
		}
		Writer output = new BufferedWriter(new FileWriter(aFile));
		try {
			output.write(content);
		} finally {
			output.close();
		}
	} catch (Exception ex) {
		ex.printStackTrace();
	}
}
 
Example 2
Source File: DiskIndex.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * initializeFrom
 * 
 * @param diskIndex
 * @param newIndexFile
 * @throws IOException
 */
private void initializeFrom(DiskIndex diskIndex, File newIndexFile) throws IOException
{
	if (newIndexFile.exists() && !newIndexFile.delete())
	{ // delete the temporary index file
		if (DEBUG)
		{
			System.out.println("initializeFrom - Failed to delete temp index " + this.indexFile); //$NON-NLS-1$
		}
	}
	else if (!newIndexFile.createNewFile())
	{
		if (DEBUG)
		{
			System.out.println("initializeFrom - Failed to create temp index " + this.indexFile); //$NON-NLS-1$
		}

		throw new IOException("Failed to create temp index " + this.indexFile); //$NON-NLS-1$
	}

	int size = diskIndex.categoryOffsets == null ? 8 : diskIndex.categoryOffsets.size();
	this.categoryOffsets = new HashMap<String, Integer>(size);
	this.categoryTables = new HashMap<String, Map<String, Object>>(size);
	this.separator = diskIndex.separator;
	this.categoriesToDiscard = diskIndex.categoriesToDiscard;
}
 
Example 3
Source File: TestUtils.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Write a byte array to a file
 * @param file to write bytearray to
 * @param array to write out
 */
public static void writeByteArrayToFile(File file, byte[] array) {
    try {
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
        FileOutputStream fos = new FileOutputStream(file);
        try {
            fos.write(array);
        }
        finally {
            fos.close();
        }
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
Source File: YarnClusterDescriptorTest.java    From flink with Apache License 2.0 6 votes vote down vote up
public void testEnvironmentDirectoryShipping(String environmentVariable) throws Exception {
	try (YarnClusterDescriptor descriptor = createYarnClusterDescriptor()) {
		File libFolder = temporaryFolder.newFolder().getAbsoluteFile();
		File libFile = new File(libFolder, "libFile.jar");
		libFile.createNewFile();

		Set<File> effectiveShipFiles = new HashSet<>();

		final Map<String, String> oldEnv = System.getenv();
		try {
			Map<String, String> env = new HashMap<>(1);
			env.put(environmentVariable, libFolder.getAbsolutePath());
			CommonTestUtils.setEnv(env);
			// only execute part of the deployment to test for shipped files
			descriptor.addEnvironmentFoldersToShipFiles(effectiveShipFiles);
		} finally {
			CommonTestUtils.setEnv(oldEnv);
		}

		// only add the ship the folder, not the contents
		Assert.assertFalse(effectiveShipFiles.contains(libFile));
		Assert.assertTrue(effectiveShipFiles.contains(libFolder));
		Assert.assertFalse(descriptor.shipFiles.contains(libFile));
		Assert.assertFalse(descriptor.shipFiles.contains(libFolder));
	}
}
 
Example 5
Source File: Config.java    From BungeePerms with GNU General Public License v3.0 6 votes vote down vote up
private void createFile()
{
    File file = new File(path);
    if (!file.exists())
    {
        file.getParentFile().mkdirs();
        try
        {
            file.createNewFile();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
 
Example 6
Source File: bug7199708.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private static File createLargeFolder() {
    try {

        File largeFolder = Files.createTempDirectory("large_folder").toFile();
        largeFolder.deleteOnExit();

        for (int i = 0; i < FILE_NUMBER; i++) {
            File file = new File(largeFolder, "File_" + i + ".txt");
            file.createNewFile();
            file.deleteOnExit();
        }
        return largeFolder;
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 7
Source File: FilesystemInterceptorTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testMoveVersionedFile_DO() throws Exception {
    File fromFile = new File(repositoryLocation, "file");
    fromFile.createNewFile();
    File toFolder = new File(repositoryLocation, "toFolder");
    toFolder.mkdirs();
    add();
    commit();
    File toFile = new File(toFolder, fromFile.getName());

    // move
    h.setFilesToRefresh(new HashSet(Arrays.asList(fromFile, toFile)));
    moveDO(fromFile, toFile);
    assertTrue(h.waitForFilesToRefresh());

    // test
    assertFalse(fromFile.exists());
    assertTrue(toFile.exists());

    assertEquals(EnumSet.of(Status.REMOVED_HEAD_INDEX, Status.REMOVED_HEAD_WORKING_TREE), getCache().getStatus(fromFile).getStatus());
    FileInformation info = getCache().getStatus(toFile);
    assertEquals(EnumSet.of(Status.NEW_HEAD_INDEX, Status.NEW_HEAD_WORKING_TREE), info.getStatus());
    assertTrue(info.isRenamed());
    assertEquals(fromFile, info.getOldFile());
}
 
Example 8
Source File: PipelineTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@Test
public void testWatchingException() throws IOException {
    pipeline.shutdown();

    BadWatcher bad = new BadWatcher(SOURCES, "md");
    pipeline = new Pipeline(mojo, FAKE, Collections.singletonList(bad), true);
    pipeline.watch();

    File dir = new File(SOURCES, "foo");
    dir.mkdirs();
    File md = new File(SOURCES, "foo/touch.md");
    md.createNewFile();
    assertThat(md.isFile()).isTrue();
    waitPullPeriod();

    // Check that the error file was created.
    File error = new File(FAKE, "target/pipeline/" + bad  + ".json");
    assertThat(error).exists();
    assertThat(FileUtils.readFileToString(error)).contains("10").contains("11").contains("touch.md").contains
            ("bad");
}
 
Example 9
Source File: UnignoreTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void test199443_GlobalIgnoreFile () throws Exception {
    File f = new File(new File(workDir, "nbproject"), "file");
    f.getParentFile().mkdirs();
    f.createNewFile();
    File ignoreFile = new File(workDir.getParentFile(), "globalignore");
    write(ignoreFile, "nbproject");
    Repository repo = getRepository(getLocalGitRepository());
    StoredConfig cfg = repo.getConfig();
    cfg.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_EXCLUDESFILE, ignoreFile.getAbsolutePath());
    cfg.save();
    GitClient client = getClient(workDir);
    assertEquals(Status.STATUS_IGNORED, client.getStatus(new File[] { f }, NULL_PROGRESS_MONITOR).get(f).getStatusIndexWC());
    
    assertEquals(new File(workDir, Constants.GITIGNORE_FILENAME), client.unignore(new File[] { f }, NULL_PROGRESS_MONITOR)[0]);
    
    write(new File(workDir, Constants.GITIGNORE_FILENAME), "/nbproject/file");
    assertEquals(new File(workDir, Constants.GITIGNORE_FILENAME), client.unignore(new File[] { f }, NULL_PROGRESS_MONITOR)[0]);
    assertEquals("!/nbproject/file", read(new File(workDir, Constants.GITIGNORE_FILENAME)));
}
 
Example 10
Source File: OperationLogger.java    From db with GNU Affero General Public License v3.0 6 votes vote down vote up
public void start(String appId, String table, String opid, OperationLogLevel logLevel) throws OperationException {
    logger.trace("OperationLogger.start(ds={0}, collection={1}, opid={2}, logLevel={4}", appId, table, opid, logLevel.getText());

    File file = new File(PathUtil.operationLogFile(appId, table, opid));
    try {
        if (!file.exists() && !file.createNewFile()) {
            throw new OperationException(ErrorCode.OPERATION_LOGGING_ERROR);
        }
    } catch (IOException ex) {
        LoggerFactory.getLogger(OperationLogger.class.getName()).error(null, ex);
        throw new OperationException(ErrorCode.OPERATION_LOGGING_ERROR);
    }

    fileMap.put(opid, file);
    delayedMessageMap.put(opid, new ArrayList<>());
    logLevelMap.put(opid, logLevel);
}
 
Example 11
Source File: VerificationCodeUtils.java    From cola-cloud with MIT License 6 votes vote down vote up
/**
 * 生成指定验证码图像文件
 *
 * @param w
 * @param h
 * @param outputFile
 * @param code
 * @throws IOException
 */
public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
    if (outputFile == null) {
        return;
    }
    File dir = outputFile.getParentFile();
    if (!dir.exists()) {
        dir.mkdirs();
    }
    try {
        outputFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(outputFile);
        outputImage(w, h, fos, code);
        fos.close();
    } catch (IOException e) {
        throw e;
    }
}
 
Example 12
Source File: ImageQueryTest.java    From CrazyWorkflowHandoutsActiviti6 with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	// 创建流程引擎
	ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
	// 得到流程存储服务对象
	RepositoryService repositoryService = engine.getRepositoryService();
	// 部署一份流程文件与相应的流程图文件
	Deployment dep = repositoryService.createDeployment()
			.addClasspathResource("MyFirstProcess.bpmn").deploy();
	// 查询流程定义
	ProcessDefinition def = repositoryService
			.createProcessDefinitionQuery().deploymentId(dep.getId())
			.singleResult();
	// 查询资源文件
	InputStream is = repositoryService.getProcessDiagram(def.getId());
	// 将输入流转换为图片对象
	BufferedImage image = ImageIO.read(is);
	// 保存为图片文件
	File file = new File("resources/result.png");
	if (!file.exists()) {
		file.createNewFile();
	}
	FileOutputStream fos = new FileOutputStream(file);
	ImageIO.write(image, "png", fos);
	fos.close();
	is.close();
	// 关闭流程引擎
	engine.close();
}
 
Example 13
Source File: FileEventLogger.java    From spring-basics-course-project with MIT License 5 votes vote down vote up
public void init() throws IOException {
	file = new File(filename);
	if (file.exists() && !file.canWrite()) {
		throw new IllegalArgumentException("Can't write to file " + filename);
	} else if (!file.exists()) {
        file.createNewFile();
	}
}
 
Example 14
Source File: TestFileHandler.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void generateLogFiles(File dir, String prefix, String sufix, int amount)
        throws IOException {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    for (int i = 0; i < amount; i++) {
        cal.add(Calendar.DAY_OF_MONTH, -1);
        File file = new File(dir, prefix + formatter.format(cal.getTime()) + sufix);
        file.createNewFile();
    }
}
 
Example 15
Source File: PluginConfigManager.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
public void replaceFileContent(String content) {
	File pluginConfigFile = new File(this.filePath);
	if (!pluginConfigFile.exists()) {
		try {
			pluginConfigFile.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	this.cleanFileContent();
	this.writeFileContent(content);
}
 
Example 16
Source File: FileSystemBlobStore.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
private boolean get(String fromBlobPath, File toFile, BlobKey blobKey) throws IOException {
	checkNotNull(fromBlobPath, "Blob path");
	checkNotNull(toFile, "File");
	checkNotNull(blobKey, "Blob key");

	if (!toFile.exists() && !toFile.createNewFile()) {
		throw new IOException("Failed to create target file to copy to");
	}

	final Path fromPath = new Path(fromBlobPath);
	MessageDigest md = BlobUtils.createMessageDigest();

	final int buffSize = 4096; // like IOUtils#BLOCKSIZE, for chunked file copying

	boolean success = false;
	try (InputStream is = fileSystem.open(fromPath);
		FileOutputStream fos = new FileOutputStream(toFile)) {
		LOG.debug("Copying from {} to {}.", fromBlobPath, toFile);

		// not using IOUtils.copyBytes(is, fos) here to be able to create a hash on-the-fly
		final byte[] buf = new byte[buffSize];
		int bytesRead = is.read(buf);
		while (bytesRead >= 0) {
			fos.write(buf, 0, bytesRead);
			md.update(buf, 0, bytesRead);

			bytesRead = is.read(buf);
		}

		// verify that file contents are correct
		final byte[] computedKey = md.digest();
		if (!Arrays.equals(computedKey, blobKey.getHash())) {
			throw new IOException("Detected data corruption during transfer");
		}

		success = true;
	} finally {
		// if the copy fails, we need to remove the target file because
		// outside code relies on a correct file as long as it exists
		if (!success) {
			try {
				toFile.delete();
			} catch (Throwable ignored) {}
		}
	}

	return true; // success is always true here
}
 
Example 17
Source File: DossierManagementImpl.java    From opencps-v2 with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Response getDossierQRcode(HttpServletRequest request, HttpHeaders header, Company company, Locale locale,
		User user, ServiceContext serviceContext, String id) {
	long groupId = GetterUtil.getLong(header.getHeaderString("groupId"));
	
	try {
		long dossierId = GetterUtil.getLong(id);
		
		Dossier dossier = DossierLocalServiceUtil.fetchDossier(dossierId);
		
		if (dossier == null) {
			dossier = DossierLocalServiceUtil.getByRef(groupId, id);
		}
		QrCode qrcode = new QrCode();
		qrcode.setHumanReadableLocation(HumanReadableLocation.BOTTOM);
		qrcode.setDataType(Symbol.DataType.HIBC);
		qrcode.setPreferredVersion(40);
		qrcode.setContent(dossier.getDossierNo());

		int width = qrcode.getWidth();
		int height = qrcode.getHeight();

		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
		Graphics2D g2d = image.createGraphics();
		Java2DRenderer renderer = new Java2DRenderer(g2d, 1, Color.WHITE, Color.BLACK);
		renderer.render(qrcode);
		File destDir = new File("barcode");
		if (!destDir.exists()) {
			destDir.mkdir();
		}
		File file = new File("barcode/" + dossier.getDossierId() + ".png");
		if (!file.exists()) {
			file.createNewFile();				
		}

		if (file.exists()) {
			ImageIO.write(image, "png", file);
//			String fileType = Files.probeContentType(file.toPath());
			ResponseBuilder responseBuilder = Response.ok((Object) file);

			responseBuilder.header("Content-Disposition",
					"attachment; filename=\"" + file.getName() + "\"");
			responseBuilder.header("Content-Type", "image/png");

			return responseBuilder.build();
		} else {
			return Response.status(HttpURLConnection.HTTP_NO_CONTENT).build();
		}

	} catch (Exception e) {
		return BusinessExceptionImpl.processException(e);
	}
}
 
Example 18
Source File: ProjectDataConverter.java    From libGDX-Path-Editor with Apache License 2.0 4 votes vote down vote up
private static void saveScreenToXML(String projPath, ScreenData scrData) throws Exception {
	String path = projPath + PATH_SEPARATOR + scrData.getXmlPath();
	File scrFile = new File(path);
	
	if (scrFile.exists()) { scrFile.delete(); }
	scrFile.createNewFile();
		
	StringWriter strWriter = new StringWriter();
	XmlWriter xmlWriter = new XmlWriter(strWriter);
	
	xmlWriter.element("screen");
	
	xmlWriter.element("name",     scrData.getName());
	xmlWriter.element("width",    scrData.getWidth());
	xmlWriter.element("height",   scrData.getHeight());
	xmlWriter.element("xmlPath",  scrData.getXmlPath());
	xmlWriter.element("jsonPath", scrData.getJsonPath());
	
	if (scrData.getBgImage() != null) {
		xmlWriter.element("bg")
				 	.element("name",        scrData.getBgImage().name)
				 	.element("type",        (getWidgetType(scrData.getBgImage()) != null) ? getWidgetType(scrData.getBgImage()).ordinal() : -1)
				 	.element("texturePath", FileUtils.getElementRelativePath(projPath, ((GdxImage)scrData.getBgImage()).getTexPath()))
				 	.element("scaleX",      scrData.getBgImage().scaleX)
				 	.element("scaleY",      scrData.getBgImage().scaleY)
				 	.element("x",           scrData.getBgImage().x)
				 	.element("y",           scrData.getBgImage().y)
				 	.element("angle",       scrData.getBgImage().rotation)
				 .pop();
	}
	
	if ((scrData.getPath() != null) && (scrData.getPath().getPath() != null)) {
		xmlWriter.element("path")
		 	.element("xmlPath",  scrData.getPath().getXmlPath())
		 	.element("jsonPath", scrData.getPath().getJsonPath())
		 .pop();
	}
	
	xmlWriter.pop();
	xmlWriter.close();
	
	FileWriter writer = new FileWriter(new File(path));
	writer.write(strWriter.toString());
	writer.close();
}
 
Example 19
Source File: FolderReaderTest.java    From baleen with Apache License 2.0 4 votes vote down vote up
@Test
public void testModifiedFile() throws Exception {
  BaleenCollectionReader bcr =
      getCollectionReader(
          FolderReader.PARAM_FOLDERS,
          new String[] {inputDir.getPath()},
          FolderReader.PARAM_REPROCESS_ON_MODIFY,
          true);

  assertFalse(bcr.doHasNext());

  File f = new File(inputDir, TEXT1_FILE);
  f.createNewFile();

  // Wait for file to be written and change detected
  Thread.sleep(TIMEOUT);

  assertTrue(bcr.doHasNext());

  bcr.getNext(jCas.getCas());
  assertFilesEquals(f.getPath(), getSource(jCas));

  jCas.reset();

  // Modify file
  Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f)));
  writer.write("Test");
  writer.close();

  Thread.sleep(TIMEOUT);

  assertTrue(bcr.doHasNext());

  bcr.getNext(jCas.getCas());

  assertFilesEquals(f.getPath(), getSource(jCas));
  assertEquals("Test", jCas.getDocumentText().trim());

  assertFalse(bcr.doHasNext());

  bcr.close();
}
 
Example 20
Source File: DataQualityTimelineService.java    From jumbune with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) throws JumbuneException,
		InterruptedException {
	DataQualityTimelineService service = new DataQualityTimelineService();
	JumbuneRequest jumbuneRequest = null;
	try {
		ReportsBean reports = new ReportsBean();
		String jumbunehome = args[1];
		
		String scheduledJobDirectoryPath = args[0];

		System.setProperty("JUMBUNE_HOME", jumbunehome);
		JumbuneInfo.setHome(args[1]);
		scheduledJobDirectoryPath = scheduledJobDirectoryPath.substring(0,
				scheduledJobDirectoryPath.lastIndexOf(File.separator));

		scheduledJobDirectoryPath = scheduledJobDirectoryPath
				+ File.separator + SCHEDULED_JSON_FILE;
		jumbuneRequest = loadJob(scheduledJobDirectoryPath, jumbunehome);
		String jobName = jumbuneRequest.getJobConfig().getJumbuneJobName();
		
		checksumFilePath = jumbunehome + DQ_DIR + jobName + File.separator + CHECKSUM_FILE;
		
		File file = new File(new StringBuilder().append(jumbunehome)
				.append(File.separator).append(TEMP)
				.append(File.separator).append("DQScheduler").append(jobName).append(".token")
				.toString());
		if(!file.getParentFile().exists() && file.getParentFile().mkdirs());
		if (file.exists()) {
			ConsoleLogUtil.CONSOLELOGGER
					.info("Other scheuled Data Quality job is running, could not execute this iteration !!!!!");
			ConsoleLogUtil.CONSOLELOGGER
					.info("Shutting down DataQuality job !!!!!");
			System.exit(1);
		} else {
			boolean launchFlag = true;
			File checksumFile = new File(checksumFilePath);
			Path path = Paths.get(checksumFilePath);
			if (!checksumFile.exists()) {
				Files.write(path, service.computeChecksumOfInputData(jumbuneRequest).getBytes(),
						StandardOpenOption.CREATE);
			} else {
				String persistedChecksum = new String(Files.readAllBytes(path));
				String computedChecksum = service.computeChecksumOfInputData(jumbuneRequest);
				if (persistedChecksum.equals(computedChecksum)) {
					launchFlag = false;
					ConsoleLogUtil.CONSOLELOGGER.info("No data changes have been detected on input path ["
							+ jumbuneRequest.getJobConfig().getHdfsInputPath()
							+ "] and hence not launching DQT Job");
				} else {
					Files.write(path, computedChecksum.getBytes(), StandardOpenOption.CREATE);
				}
			}
			if (launchFlag) {
				file.createNewFile();
				service.run(jumbuneRequest, reports, jumbunehome);
			}					
		}
		System.exit(0);
	} catch (Exception e) {
		LOGGER.error(e);
		System.exit(1);
	}
}