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.compomics.pladipus.core.control.util.ZipUtils.java

/**
 * Zips an entire folder in one go//  w w w.j  av  a  2s  .  c o m
 *
 * @param input the original folder
 * @param output the destination zip file
 */
static public void zipFolder(File inputFolder, File zipFile) throws UnspecifiedPladipusException, IOException {
    if (zipFile.exists()) {
        zipFile.delete();
    }
    zipFile.getParentFile().mkdirs();
    zipFile.createNewFile();
    try (FileOutputStream fileWriter = new FileOutputStream(zipFile);
            ZipOutputStream zip = new ZipOutputStream(fileWriter)) {
        addFolderToZip("", inputFolder.getAbsolutePath(), zip);
        zip.flush();
    }
}

From source file:Util.java

/**
 * Creates a file, making sure that its name is unique.
*  The file will be created as if by <tt>new File(dir, prefix+i+extension)</tt>,
*  where i is an integer chosen such that the returned File does not exist.
* @param dir Directory to use for the returned file
* @param prefix Prefix of the file name (before the uniquifying integer)
* @param extension Suffix of the file name (after the uniquifying integer)
 *//*  w w w  .  j a  v  a  2s . c o m*/
public static File uniqueFile(File dir, String prefix, String extension) throws IOException {
    File f = null;
    int i = 0;
    boolean wasCreated = false;
    while (!wasCreated) {
        if (dir != null) {
            f = new File(dir, prefix + i + extension);
        } else {
            f = new File(prefix + i + extension);
        }
        wasCreated = f.createNewFile();
        i++;
    }
    return f;
}

From source file:com.bc.fiduceo.TestUtil.java

public static void storeProperties(Properties properties, File configDir, String child) throws IOException {
    final File propertiesFile = new File(configDir, child);
    if (!propertiesFile.createNewFile()) {
        fail("unable to create test file: " + propertiesFile.getAbsolutePath());
    }//  www  . j av  a2 s  .c o m

    FileOutputStream outputStream = null;
    try {
        outputStream = new FileOutputStream(propertiesFile);
        properties.store(outputStream, "");
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }
}

From source file:Main.java

public static void saveImage(String imagePath, Bitmap bm) {

    if (bm == null || imagePath == null || "".equals(imagePath)) {
        return;/*from  w  w  w.j  a  v a 2s  .c  o  m*/
    }

    File f = new File(imagePath);
    if (f.exists()) {
        return;
    } else {
        try {
            File parentFile = f.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            f.createNewFile();
            FileOutputStream fos;
            fos = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.close();
        } catch (FileNotFoundException e) {
            f.delete();
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            f.delete();
        }
    }
}

From source file:azkaban.migration.schedule2trigger.Schedule2Trigger.java

private static void writeScheduleFile(azkaban.migration.scheduler.Schedule sched, File outputDir)
        throws IOException {
    String scheduleFileName = sched.getProjectName() + "-" + sched.getFlowName();
    File outputFile = new File(outputDir, scheduleFileName);
    outputFile.createNewFile();
    Props props = new Props();
    props.put("flowName", sched.getFlowName());
    props.put("projectName", sched.getProjectName());
    props.put("projectId", String.valueOf(sched.getProjectId()));
    props.put("period", azkaban.migration.scheduler.Schedule.createPeriodString(sched.getPeriod()));
    props.put("firstScheduleTimeLong", sched.getFirstSchedTime());
    props.put("lastScheduleTimeLong", sched.getLastSchedTime());
    props.put("timezone", sched.getTimezone().getID());
    props.put("submitUser", sched.getSubmitUser());
    props.put("submitTimeLong", sched.getSubmitTime());
    props.put("nextExecTimeLong", sched.getNextExecTime());

    ExecutionOptions executionOptions = sched.getExecutionOptions();
    if (executionOptions != null) {
        props.put("executionOptionsObj", JSONUtils.toJSON(executionOptions.toObject()));
    }/*  w  w  w  .  j  a  v a2s . c  om*/

    azkaban.migration.sla.SlaOptions slaOptions = sched.getSlaOptions();
    if (slaOptions != null) {

        List<Map<String, Object>> settingsObj = new ArrayList<Map<String, Object>>();
        List<azkaban.migration.sla.SLA.SlaSetting> settings = slaOptions.getSettings();
        for (azkaban.migration.sla.SLA.SlaSetting set : settings) {
            Map<String, Object> setObj = new HashMap<String, Object>();
            String setId = set.getId();
            azkaban.migration.sla.SLA.SlaRule rule = set.getRule();
            Map<String, Object> info = new HashMap<String, Object>();
            info.put(INFO_DURATION, azkaban.migration.scheduler.Schedule.createPeriodString(set.getDuration()));
            info.put(INFO_EMAIL_LIST, slaOptions.getSlaEmails());
            List<String> actionsList = new ArrayList<String>();
            for (azkaban.migration.sla.SLA.SlaAction act : set.getActions()) {
                if (act.equals(azkaban.migration.sla.SLA.SlaAction.EMAIL)) {
                    actionsList.add(ACTION_ALERT);
                    info.put(ALERT_TYPE, "email");
                } else if (act.equals(azkaban.migration.sla.SLA.SlaAction.KILL)) {
                    actionsList.add(ACTION_CANCEL_FLOW);
                }
            }
            setObj.put("actions", actionsList);
            if (setId.equals("")) {
                info.put(INFO_FLOW_NAME, sched.getFlowName());
                if (rule.equals(azkaban.migration.sla.SLA.SlaRule.FINISH)) {
                    setObj.put("type", TYPE_FLOW_FINISH);
                } else if (rule.equals(azkaban.migration.sla.SLA.SlaRule.SUCCESS)) {
                    setObj.put("type", TYPE_FLOW_SUCCEED);
                }
            } else {
                info.put(INFO_JOB_NAME, setId);
                if (rule.equals(azkaban.migration.sla.SLA.SlaRule.FINISH)) {
                    setObj.put("type", TYPE_JOB_FINISH);
                } else if (rule.equals(azkaban.migration.sla.SLA.SlaRule.SUCCESS)) {
                    setObj.put("type", TYPE_JOB_SUCCEED);
                }
            }
            setObj.put("info", info);
            settingsObj.add(setObj);
        }

        props.put("slaOptionsObj", JSONUtils.toJSON(settingsObj));
    }
    props.storeLocal(outputFile);
}

From source file:com.splunk.shuttl.testutil.TUtilsFile.java

/**
 * @return a temporary, existing, empty file that will be deleted when the VM
 *         terminates.//from  w  w  w.  j  a  v  a 2s .  co m
 * 
 * @see TUtilsFile#createFilePath()
 */
public static File createFile() {
    File uniquelyNamedFile = getUniquelyNamedFileWithPrefix("test-file");
    try {
        if (!uniquelyNamedFile.createNewFile())
            throw new IOException("Could not create file: " + uniquelyNamedFile);
        FileUtils.forceDeleteOnExit(uniquelyNamedFile);
    } catch (IOException e) {
        TUtilsTestNG.failForException("Couldn't create a test file.", e);
    }
    return uniquelyNamedFile;
}

From source file:bammerbom.ultimatecore.bukkit.resources.classes.ErrorLogger.java

public static void log(Throwable t, String s) {
    String time = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss-SSS").format(Calendar.getInstance().getTime());
    File dir = new File(Bukkit.getPluginManager().getPlugin("UltimateCore").getDataFolder() + "/Errors");
    if (!dir.exists()) {
        dir.mkdir();//from  w  w w .j a  v a  2  s.  c o m
    }
    File file = new File(Bukkit.getPluginManager().getPlugin("UltimateCore").getDataFolder() + "/Errors",
            time + ".txt");
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    FileWriter outFile;
    try {
        outFile = new FileWriter(file);
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
    PrintWriter out = new PrintWriter(outFile);
    out.println("=======================================");
    out.println("UltimateCore has run into an error ");
    out.println("Please report your error on dev.bukkit.org/bukkit-plugins/ultimate_core/create-ticket");
    out.println("Bukkit version: " + Bukkit.getServer().getVersion());
    out.println("UltimateCore version: " + r.getUC().getDescription().getVersion());
    out.println("Plugins loaded (" + Bukkit.getPluginManager().getPlugins().length + "): "
            + Arrays.asList(Bukkit.getPluginManager().getPlugins()));
    out.println("Java version: " + System.getProperty("java.version"));
    out.println("OS info: " + System.getProperty("os.arch") + ", " + System.getProperty("os.name") + ", "
            + System.getProperty("os.version"));
    out.println("Time: " + time);
    out.println("Error message: " + t.getMessage());
    out.println("UltimateCore message: " + s);
    out.println("=======================================");
    out.println("Stacktrace: \n" + ExceptionUtils.getStackTrace(t));
    out.println("=======================================");
    out.close();
    try {
        outFile.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //
    Bukkit.getConsoleSender().sendMessage(" ");
    r.log(ChatColor.DARK_RED + "=========================================================");
    r.log(ChatColor.RED + "UltimateCore has run into an error ");
    r.log(ChatColor.RED + "Please report your error on ");
    r.log(ChatColor.YELLOW + "http://dev.bukkit.org/bukkit-plugins/ultimate_core/create-ticket");
    r.log(ChatColor.RED + "Include the file: ");
    r.log(ChatColor.YELLOW + "plugins/UltimateCore/Errors/" + time + ".txt ");
    /*r.log(ChatColor.RED + "Bukkit version: " + Bukkit.getServer().getVersion());
     r.log(ChatColor.RED + "UltimateCore version: " + Bukkit.getPluginManager().getPlugin("UltimateCore").getDescription().getVersion());
     r.log(ChatColor.RED + "Plugins loaded (" + Bukkit.getPluginManager().getPlugins().length + "): " + Arrays.asList(Bukkit.getPluginManager().getPlugins()));
     r.log(ChatColor.RED + "Java version: " + System.getProperty("java.version"));
     r.log(ChatColor.RED + "OS info: " + System.getProperty("os.arch") + ", " + System.getProperty("os.name") + ", " + System.getProperty("os.version"));
     r.log(ChatColor.RED + "Error message: " + t.getMessage());
     r.log(ChatColor.RED + "UltimateCore message: " + s);*/
    r.log(ChatColor.DARK_RED + "=========================================================");
    if (t instanceof Exception) {
        r.log(ChatColor.RED + "Stacktrace: ");
        t.printStackTrace();
        r.log(ChatColor.DARK_RED + "=========================================================");
    }
    Bukkit.getConsoleSender().sendMessage(" ");
}

From source file:Main.java

/**
 * Stores document into specified file/*w w  w.j a  v  a 2 s. c  om*/
 * @param document XML document
 * @param transformer Transformer object to store document
 * @param file File where this method stores XML document
 * @param encoding Encoding in with document should be stored
 * @throws IOException If cannot store because of IO error
 * @throws TransformerException If cannot store because transformer error
 */
public static void storeDocument(Document document, Transformer transformer, File file, String encoding)
        throws IOException, TransformerException {
    FileOutputStream stream = null;
    OutputStreamWriter writer = null;
    try {
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        stream = new FileOutputStream(file);
        writer = new OutputStreamWriter(stream, encoding);
        storeDocument(document, transformer, writer);
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}

From source file:io.crate.testing.Utils.java

static void uncompressTarGZ(File tarFile, File dest) throws IOException {
    TarArchiveInputStream tarIn = new TarArchiveInputStream(
            new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(tarFile))));

    TarArchiveEntry tarEntry = tarIn.getNextTarEntry();
    // tarIn is a TarArchiveInputStream
    while (tarEntry != null) {
        Path entryPath = Paths.get(tarEntry.getName());

        if (entryPath.getNameCount() == 1) {
            tarEntry = tarIn.getNextTarEntry();
            continue;
        }/* w  w w  . ja v  a2s .  c  o  m*/

        Path strippedPath = entryPath.subpath(1, entryPath.getNameCount());
        File destPath = new File(dest, strippedPath.toString());

        if (tarEntry.isDirectory()) {
            destPath.mkdirs();
        } else {
            destPath.createNewFile();
            byte[] btoRead = new byte[1024];
            BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath));
            int len;
            while ((len = tarIn.read(btoRead)) != -1) {
                bout.write(btoRead, 0, len);
            }

            bout.close();
            if (destPath.getParent().equals(dest.getPath() + "/bin")) {
                destPath.setExecutable(true);
            }
        }
        tarEntry = tarIn.getNextTarEntry();
    }
    tarIn.close();
}

From source file:com.bc.fiduceo.TestUtil.java

public static void writeMmdWriterConfig(File configDir, String xml) throws IOException {
    final File propertiesFile = new File(configDir, "mmd-writer-config.xml");
    if (!propertiesFile.createNewFile()) {
        fail("unable to create test file: " + propertiesFile.getAbsolutePath());
    }/*from w  w w. ja  v a2 s . com*/

    writeStringTo(propertiesFile, xml);
}