下面列出了java.io.File#createNewFile ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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();
}
}
/**
* 生成指定验证码图像文件
*
* @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;
}
}
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);
}
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)));
}
@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");
}
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());
}
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);
}
}
private void createFile()
{
File file = new File(path);
if (!file.exists())
{
file.getParentFile().mkdirs();
try
{
file.createNewFile();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
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));
}
}
/**
* 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);
}
}
/**
* 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;
}
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);
}
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();
}
}
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();
}
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();
}
}
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
}
@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);
}
}
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();
}
@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();
}
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);
}
}