Example usage for java.io File createNewFile

List of usage examples for java.io File createNewFile

Introduction

In this page you can find the example usage for java.io File createNewFile.

Prototype

public boolean createNewFile() throws IOException 

Source Link

Document

Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.

Usage

From source file:com.baasbox.configuration.IosCertificateHandler.java

public static void init() {
    String folder = BBConfiguration.getPushCertificateFolder();
    File f = new File(folder);
    if (!f.exists()) {
        f.mkdirs();//w ww.  j a  va 2  s  .co  m
    }
    ConfigurationFileContainer prod = Push.PROFILE1_PRODUCTION_IOS_CERTIFICATE.getValueAsFileContainer();
    ConfigurationFileContainer sandbox = Push.PROFILE1_SANDBOX_IOS_CERTIFICATE.getValueAsFileContainer();

    ConfigurationFileContainer prod2 = Push.PROFILE2_PRODUCTION_IOS_CERTIFICATE.getValueAsFileContainer();
    ConfigurationFileContainer sandbox2 = Push.PROFILE2_SANDBOX_IOS_CERTIFICATE.getValueAsFileContainer();

    ConfigurationFileContainer prod3 = Push.PROFILE3_PRODUCTION_IOS_CERTIFICATE.getValueAsFileContainer();
    ConfigurationFileContainer sandbox3 = Push.PROFILE3_SANDBOX_IOS_CERTIFICATE.getValueAsFileContainer();

    if (prod != null) {
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Creating production certificate for default profile:" + prod.getName());
        File prodCertificate = new File(folder + sep + prod.getName());
        if (!prodCertificate.exists()) {
            try {
                prodCertificate.createNewFile();
                ByteArrayInputStream bais = new ByteArrayInputStream(prod.getContent());
                FileUtils.copyInputStreamToFile(bais, prodCertificate);

            } catch (Exception e) {
                prodCertificate.delete();
                throw new RuntimeException(
                        "Unable to create file for certificate:" + ExceptionUtils.getMessage(e));
            }
        }
    }
    if (sandbox != null) {
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Creating sandbox certificate for default profile:" + sandbox.getName());
        File sandboxCertificate = new File(folder + sep + sandbox.getName());
        if (!sandboxCertificate.exists()) {
            try {
                sandboxCertificate.createNewFile();
                ByteArrayInputStream bais = new ByteArrayInputStream(sandbox.getContent());
                FileUtils.copyInputStreamToFile(bais, sandboxCertificate);

            } catch (Exception e) {
                sandboxCertificate.delete();
                throw new RuntimeException(
                        "Unable to create file for certificate:" + ExceptionUtils.getMessage(e));
            }
        }
    }

    if (prod2 != null) {
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Creating production certificate for profile 2:" + prod2.getName());
        File prodCertificate = new File(folder + sep + prod2.getName());
        if (!prodCertificate.exists()) {
            try {
                prodCertificate.createNewFile();
                ByteArrayInputStream bais = new ByteArrayInputStream(prod.getContent());
                FileUtils.copyInputStreamToFile(bais, prodCertificate);

            } catch (Exception e) {
                prodCertificate.delete();
                throw new RuntimeException(
                        "Unable to create file for certificate:" + ExceptionUtils.getMessage(e));
            }
        }
    }
    if (sandbox2 != null) {
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Creating sandbox certificate for profile 2:" + sandbox2.getName());
        File sandboxCertificate = new File(folder + sep + sandbox2.getName());
        if (!sandboxCertificate.exists()) {
            try {
                sandboxCertificate.createNewFile();
                ByteArrayInputStream bais = new ByteArrayInputStream(sandbox.getContent());
                FileUtils.copyInputStreamToFile(bais, sandboxCertificate);

            } catch (Exception e) {
                sandboxCertificate.delete();
                throw new RuntimeException(
                        "Unable to create file for certificate:" + ExceptionUtils.getMessage(e));
            }
        }
    }

    if (prod3 != null) {
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Creating production certificate for profile 3:" + prod3.getName());
        File prodCertificate = new File(folder + sep + prod3.getName());
        if (!prodCertificate.exists()) {
            try {
                prodCertificate.createNewFile();
                ByteArrayInputStream bais = new ByteArrayInputStream(prod3.getContent());
                FileUtils.copyInputStreamToFile(bais, prodCertificate);

            } catch (Exception e) {
                prodCertificate.delete();
                throw new RuntimeException(
                        "Unable to create file for certificate:" + ExceptionUtils.getMessage(e));
            }
        }
    }
    if (sandbox3 != null) {
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Creating sandbox certificate for profile 3:" + sandbox3.getName());
        File sandboxCertificate = new File(folder + sep + sandbox3.getName());
        if (!sandboxCertificate.exists()) {
            try {
                sandboxCertificate.createNewFile();
                ByteArrayInputStream bais = new ByteArrayInputStream(sandbox.getContent());
                FileUtils.copyInputStreamToFile(bais, sandboxCertificate);

            } catch (Exception e) {
                sandboxCertificate.delete();
                throw new RuntimeException(
                        "Unable to create file for certificate:" + ExceptionUtils.getMessage(e));
            }
        }
    }

}

From source file:com.alibaba.otter.shared.common.utils.NioUtilsPerformance.java

public static void channelTest(File source, File target) throws Exception {
    FileInputStream fis = null;//from  w w  w . j a  v a  2s .  c om
    FileOutputStream fos = null;
    try {
        fis = new FileInputStream(source);
        fos = new FileOutputStream(target);
        FileChannel sChannel = fis.getChannel();
        FileChannel tChannel = fos.getChannel();

        target.createNewFile();

        ByteBuffer buffer = ByteBuffer.allocate(16 * 1024);
        while (sChannel.read(buffer) > 0) {
            buffer.flip();
            tChannel.write(buffer);
            buffer.clear();
        }

        tChannel.close();
        sChannel.close();
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(fos);
    }
}

From source file:com.simas.vc.background_tasks.FFprobe.java

/**
 * This operation is synchronous and cannot be run on the UI thread.
 *//*w  ww  . jav  a2 s  .co  m*/
@SuppressWarnings("ResultOfMethodCallIgnored")
public synchronized static FileAttributes parseAttributes(File inputFile) throws VCException {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        throw new IllegalStateException("parseAttributes cannot be run on the UI thread!");
    }

    /* Executable call used
       ./ffprobe -i 'nature/bee.mp4' \
       -v quiet -print_format json \
       -show_format -show_entries format=duration,size,format_name,format_long_name,filename,nb_streams \
       -show_streams -show_entries stream=codec_name,codec_long_name,codec_type,sample_rate,channels,duration,display_aspect_ratio,width,height,time_base,codec_time_base,r_frame_rate
    */

    // Check if input exists
    if (!inputFile.exists()) {
        throw new VCException(Utils.getString(R.string.input_not_found));
    }

    // Create a temporary file to hold the stdout output
    File tmpFile;
    try {
        tmpFile = File.createTempFile("vc-out", null);
        tmpFile.delete();
        tmpFile.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
        throw new VCException(Utils.getString(R.string.tmp_not_created));
    }

    // Create arguments for ffprobe
    final String[] args = new ArgumentBuilder(TAG).add("-i").addSpaced("%s", inputFile.getPath()) // Spaced input file path
            .add("-v quiet -print_format json") // Output quietly in JSON
            // Format entries to show
            .add("-show_format -show_entries format=%s,%s,%s,%s,%s,%s",
                    Utils.getString(R.string.format_duration), Utils.getString(R.string.format_size),
                    Utils.getString(R.string.format_name), Utils.getString(R.string.format_long_name),
                    Utils.getString(R.string.format_filename), Utils.getString(R.string.format_stream_count))
            // Stream entries to show
            .add("-show_streams -show_entries stream=%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s",
                    Utils.getString(R.string.stream_name), Utils.getString(R.string.stream_long_name),
                    Utils.getString(R.string.stream_type), Utils.getString(R.string.stream_sample_rate),
                    Utils.getString(R.string.stream_channels), Utils.getString(R.string.stream_duration),
                    Utils.getString(R.string.stream_aspect_ratio), Utils.getString(R.string.stream_width),
                    Utils.getString(R.string.stream_height), Utils.getString(R.string.stream_tbn),
                    Utils.getString(R.string.stream_tbc), Utils.getString(R.string.stream_tbr),
                    Utils.getString(R.string.stream_codec_tag))
            .build();

    if (cFFprobe(args, tmpFile.getPath()) != 0) {
        throw new VCException(Utils.getString(R.string.ffprobe_fail));
    }

    BufferedReader reader = null;
    FileAttributes fa = null;
    try {
        // Parse file
        reader = new BufferedReader(new FileReader(tmpFile));
        StringBuilder sb = new StringBuilder();
        String line = reader.readLine();

        while (line != null) {
            sb.append(line);
            sb.append('\n');
            line = reader.readLine();
        }
        String content = sb.toString();

        int firstOpeningBrace = content.indexOf('{');
        int lastClosingBrace = content.lastIndexOf('}');
        if (firstOpeningBrace == -1 || lastClosingBrace == -1) {
            return null;
        }
        String json = content.substring(firstOpeningBrace, lastClosingBrace + 1);

        // Parse JSON
        fa = parseJsonAttributes(json);
        Log.i(TAG, "Parsed attributes: " + fa);
    } catch (IOException e) {
        e.printStackTrace();
        throw new VCException(Utils.getString(R.string.ffprobe_fail));
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // Delete the tmp file
    tmpFile.delete();

    // No support for files with no audio/video streams (for now?)
    if (fa != null) {
        if (fa.getAudioStreams().size() == 0) {
            throw new VCException(Utils.getString(R.string.audioless_unsupported));
        } else if (fa.getVideoStreams().size() == 0) {
            throw new VCException(Utils.getString(R.string.videoless_unsupported));
        }
    }

    return fa;
}

From source file:net.lyonlancer5.mcmp.karasu.util.ModFileUtils.java

static long download(String url, File output) throws IOException {
    URL url1 = new URL(url);
    ReadableByteChannel rbc = Channels.newChannel(url1.openStream());
    FileOutputStream fos = new FileOutputStream(output);

    if (!output.exists()) {
        output.getParentFile().mkdirs();
        output.createNewFile();
    }// w ww. jav a2s .  c o  m

    long f = fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
    fos.close();
    return f;
}

From source file:io.joynr.util.JoynrUtil.java

public static void writeResource(byte[] byteResource, String fileName) throws IOException {
    File file = new File(fileName);
    if (!file.exists()) {
        createDir(file.getParentFile().getAbsolutePath());
    }/*w  w  w .j a  v  a 2 s.co m*/

    if (!file.createNewFile()) {
        logger.debug("Creating file " + fileName + " failed.");
    }

    FileOutputStream outputStream = null;
    try {
        outputStream = new FileOutputStream(fileName);
        outputStream.write(byteResource);

    } catch (FileNotFoundException e) {
        logger.error("Writing file " + fileName + " failed.", e);
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }

    }

}

From source file:de.teamgrit.grit.report.PlainGenerator.java

/**
 * This method creates a plain-text file from a SubmissionObj instance.
 * //www.  ja  v a  2 s  . c o  m
 * @param submission
 *            A SubmissionObj containing the information that the content
 *            gets generated from.
 * @param outdir
 *            the output directory
 * @param courseName
 *            the name of the Course
 * @param exerciseName
 *            the name of the exercise
 * @return The Path to the created plain-text file.
 * @throws IOException
 *             If something goes wrong when writing.
 */
public static Path generatePlain(final Submission submission, final Path outdir, String courseName,
        String exerciseName) throws IOException {
    final File location = outdir.toFile();

    File outputFile = new File(location, submission.getStudent().getName() + ".report.txt");
    if (Files.exists(outputFile.toPath(), LinkOption.NOFOLLOW_LINKS)) {
        Files.delete(outputFile.toPath());
    }
    outputFile.createNewFile();

    writeHeader(outputFile, submission, courseName, exerciseName);
    writeOverview(outputFile, submission);
    writeTestResult(outputFile, submission);

    // if there are compile errors, put these in the text file instead of
    // JUnit Test result
    CheckingResult checkingResult = submission.getCheckingResult();
    if (checkingResult.getCompilerOutput().compilerStreamBroken()) {
        writeCompilerErrors(outputFile, submission);
    } else {
        TestOutput testResults = checkingResult.getTestResults();
        if ((testResults.getPassedTestCount() < testResults.getTestCount()) && testResults.getDidTest()) {
            writeFailedTests(outputFile, submission);
        }
    }

    writeCompilerOutput(outputFile, submission);

    return outputFile.toPath();
}

From source file:Main.java

public static boolean createFile(File file, boolean forceCreate) throws IOException {
    if (file == null) {
        return false;
    }/* w w  w . j  a  v  a 2 s .co m*/

    if (file.exists()) {
        if (!forceCreate) {
            return false;
        } else {
            file.delete();
        }
    }

    if (!isExistDirectory(file.getParentFile().getAbsolutePath())) {
        file.getParentFile().mkdirs();
    }

    return file.createNewFile();
}

From source file:net.ftb.util.FileUtils.java

public static void copyFile(File sourceFile, File destinationFile, boolean overwrite) throws IOException {
    if (sourceFile.exists()) {
        if (!destinationFile.exists()) {
            destinationFile.getParentFile().mkdirs();
            destinationFile.createNewFile();
        } else if (!overwrite)
            return;
        FileChannel sourceStream = null, destinationStream = null;
        try {//from  ww  w .  j  a  va 2s .  c o m
            sourceStream = new FileInputStream(sourceFile).getChannel();
            destinationStream = new FileOutputStream(destinationFile).getChannel();
            destinationStream.transferFrom(sourceStream, 0, sourceStream.size());
        } finally {
            if (sourceStream != null) {
                sourceStream.close();
            }
            if (destinationStream != null) {
                destinationStream.close();
            }
        }
    }
}

From source file:ch.ivyteam.ivy.maven.TestInstallEngineMojo.java

private static File createFakeEngineDir(String ivyVersion) throws IOException {
    File fakeDir = createTempDir("fake");
    File fakeLibToDeclareVersion = new File(fakeDir, getFakeLibraryPath(ivyVersion));
    fakeLibToDeclareVersion.getParentFile().mkdirs();
    fakeLibToDeclareVersion.createNewFile();
    return fakeDir;
}

From source file:org.envirocar.app.util.Util.java

/**
 * Create a file in the .enviroCar folder of the external storage.
 * /* w w  w .jav a2s . co m*/
 * @param fileName
 *            the name of the new file
 * @return the resulting file
 * @throws IOException
 */
public static File createFileOnExternalStorage(String fileName) throws IOException {
    File directory = resolveExternalStorageBaseFolder();

    File f = new File(directory, fileName);
    f.createNewFile();
    if (!f.isFile()) {
        throw new IOException(fileName + " is not a file!");
    }
    return f;
}