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:net.mindengine.blogix.BlogixMain.java

private static void createPostTo(String folderName, String id, String title) throws Exception {
    if (title.isEmpty()) {
        error("Title should not be empty");
    }// w  w  w. ja v a  2s. c om
    StringBuffer buff = new StringBuffer();
    buff.append("--------------------------------\n");
    buff.append("title\n");
    buff.append("   ");
    buff.append(title);
    buff.append("\n");
    buff.append("--------------------------------\n");
    buff.append("date\n");
    buff.append("   ");
    buff.append(currentDateInBlogixFormat());
    buff.append("\n");
    buff.append("--------------------------------\n");
    buff.append("allowComments\n");
    buff.append("   true");
    buff.append("\n");
    buff.append("--------------------------------\n");
    buff.append("categories\n");
    buff.append("   \n================================\n");

    String fullPath = "db" + File.separator + folderName + File.separator + id + _BLOGIX_SUFFIX;
    File file = new File(fullPath);
    file.createNewFile();
    FileUtils.writeStringToFile(file, buff.toString());
    info("created " + fullPath);
}

From source file:main.RankerOCR.java

/**
 * Evaluate any output files parameters.
 * <p>//from w  w w  . jav a  2 s .c  o m
 * @param s File path as a string
 * @param c Separator charter, require if must to create a new file
 * @return File if possible. Otherwise, stop the program and return an error
 * code
 */
private static File evalOutputFile(String s, char c) {
    File f = new File(s);
    if (!f.exists()) {
        try {
            f.createNewFile();
            //Write CSV title
            String[] t = { "Difference %", "Ranker name", "Original name", "Comparative name", "Original path",
                    "Comparative path", "Date & Time" };
            writeOutpuDocCsv(f, c, t);
        } catch (IOException ex) {
            printFormated(ex.getLocalizedMessage());
            System.exit(-35);
        }
    }
    if (!f.canWrite()) {
        printFormated("Can not write : " + s);
        System.exit(-34);
    }
    return f;
}

From source file:com.justgiving.raven.kissmetrics.utils.KissmetricsRowParser.java

public static void runonfileValidJson(String input_filename, String output_filename) throws IOException {
    InputStream fis;//from   ww  w.  j a v  a  2s. co  m
    BufferedReader bufferdReader;
    String line;

    try {
        File file = new File(output_filename);
        if (file.createNewFile()) {
            logger.warn("File has been created");
        } //else {
          //   logger.info("File already exists.");
          //}
          // if (!file.getParentFile().mkdirs())
          // throw new IOException("Unable to create " +
          // file.getParentFile());

        FileWriter fileWriter = new FileWriter(output_filename, false);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        String parsedLine;
        fis = new FileInputStream(input_filename);
        bufferdReader = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
        while ((line = bufferdReader.readLine()) != null) {
            parsedLine = runOnStringJson(new Text(line), output_filename) + "\n";
            bufferedWriter.write(parsedLine);
        }
        bufferedWriter.close();
        bufferdReader.close();
    } catch (IOException e) {
        logger.error("Error writing to file '" + output_filename + "'");
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    logger.info("Ouput written to " + output_filename);
}

From source file:org.eclipse.virgo.ide.jdt.internal.core.classpath.ServerClasspathUtils.java

/**
 * Saves the contents of the given {@link StringBuilder} into the settings file
 *//*from  ww w.j  av a 2s .c o  m*/
private static void saveFile(final IJavaProject project, final StringBuilder builder) {

    // Get the file from the project
    File file = new File(ServerCorePlugin.getDefault().getStateLocation().toFile(),
            project.getProject().getName() + CLASSPATH_FILE);
    FileOutputStream os = null;
    try {

        // Create a new file; override old file
        file.createNewFile();

        // Write the contents of the StringBuilder
        os = new FileOutputStream(file);
        os.write(builder.toString().getBytes("UTF-8"));
        os.flush();
    } catch (UnsupportedEncodingException e) {
        // can't happen as default UTF-8 is used
    } catch (IOException e) {
        JdtCorePlugin.log("Cannot save classpath entries to '" + file.getAbsolutePath() + "'", e);
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
            }
        }
    }

}

From source file:com.doplgangr.secrecy.FileSystem.storage.java

public static Uri saveThumbnail(Context context, Uri uri, String filename) {
    InputStream stream = null;/* w  w  w.j a  va 2  s .  c om*/
    try {
        stream = context.getContentResolver().openInputStream(uri);
        java.io.File thumbpath = new java.io.File(getAbsTempFolder() + "/" + "_thumb" + filename);
        if (thumbpath.exists())
            storage.purgeFile(thumbpath);
        thumbpath.createNewFile();
        FileOutputStream out = new FileOutputStream(thumbpath);
        Bitmap bitmap = decodeSampledBitmapFromPath(getPath(context, uri), 150, 150);
        if (bitmap == null) { //If photo fails, try Video
            Util.log(getPath(context, uri));
            bitmap = ThumbnailUtils.createVideoThumbnail(getPath(context, uri),
                    MediaStore.Video.Thumbnails.MICRO_KIND);
        }
        if (bitmap == null) {
            out.close();
            storage.purgeFile(thumbpath);
            return null;
        }
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.close();
        return Uri.fromFile(thumbpath);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (stream != null)
            try {
                stream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
    }
    return null;
}

From source file:Main.java

/**
 * Copy a file into a dstPath directory.
 * The output filename can be provided.//ww  w  . ja  v  a 2 s  .  co  m
 * The output file is not overriden if it is already exist.
 * @param context the context
 * @param sourceFile the file source path
 * @param dstDirPath the dst path
 * @param outputFilename optional the output filename
 * @return the downloads file path if the file exists or has been properly saved
 */
public static String saveFileInto(Context context, File sourceFile, String dstDirPath, String outputFilename) {
    // sanity check
    if ((null == sourceFile) || (null == dstDirPath)) {
        return null;
    }

    // defines another name for the external media
    String dstFileName;

    // build a filename is not provided
    if (null == outputFilename) {
        // extract the file extension from the uri
        int dotPos = sourceFile.getName().lastIndexOf(".");

        String fileExt = "";
        if (dotPos > 0) {
            fileExt = sourceFile.getName().substring(dotPos);
        }

        dstFileName = "MatrixConsole_" + System.currentTimeMillis() + fileExt;
    } else {
        dstFileName = outputFilename;
    }

    File dstDir = Environment.getExternalStoragePublicDirectory(dstDirPath);
    if (dstDir != null) {
        dstDir.mkdirs();
    }

    File dstFile = new File(dstDir, dstFileName);

    // Copy source file to destination
    FileInputStream inputStream = null;
    FileOutputStream outputStream = null;
    try {
        // create only the
        if (!dstFile.exists()) {
            dstFile.createNewFile();

            inputStream = new FileInputStream(sourceFile);
            outputStream = new FileOutputStream(dstFile);

            byte[] buffer = new byte[1024 * 10];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        }
    } catch (Exception e) {
        dstFile = null;
    } finally {
        // Close resources
        try {
            if (inputStream != null)
                inputStream.close();
            if (outputStream != null)
                outputStream.close();
        } catch (Exception e) {
        }
    }

    if (null != dstFile) {
        return dstFile.getAbsolutePath();
    } else {
        return null;
    }
}

From source file:com.bb.extensions.plugin.unittests.internal.utilities.FileUtils.java

/**
 * Copy sourceFile to destFile//ww w . ja  va  2  s  .  c  o  m
 * 
 * @param sourceFile
 *            The source file to copy from
 * @param destFile
 *            The destination file to copy to
 * @throws IOException
 */
public static void copyFile(File sourceFile, File destFile) throws IOException {
    if (!destFile.exists()) {
        destFile.createNewFile();
    }

    FileChannel source = null;
    FileChannel destination = null;

    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();
        destination.transferFrom(source, 0, source.size());
    } finally {
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
}

From source file:net.portalblock.untamedchat.bungee.UCConfig.java

public static void load() {
    final String NEW_LINE = System.getProperty("line.separator");
    File cfgDir = new File("plugins/UntamedChat");
    if (!cfgDir.exists()) {
        UntamedChat.getInstance().getLogger().info("No config directory found, generating one now!");
        cfgDir.mkdir();//from  w  w w .  ja  va 2 s . c  o  m
    }
    File configFile = new File(cfgDir + "/config.json");
    if (!configFile.exists()) {
        UntamedChat.getInstance().getLogger().info("No config file found, generating one now!");
        try {
            configFile.createNewFile();
            InputStream is = UCConfig.class.getResourceAsStream("/config.json");
            String line;
            if (is == null)
                throw new NullPointerException("is");
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            FileWriter configWriter = new FileWriter(configFile);
            while ((line = reader.readLine()) != null) {
                configWriter.write(line + NEW_LINE);
            }
            configWriter.flush();
            configWriter.close();
            reader.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        BufferedReader reader = new BufferedReader(new FileReader(configFile));
        StringBuilder configBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            configBuilder.append(line);
        }
        JSONObject config = new JSONObject(configBuilder.toString());
        TARGET_FORMAT = config.optString("target_format", "&6{sender} &7-> &6Me&7: {msg}");
        SENDER_FORMAT = config.optString("sender_format", "&6Me &7-> &6{target}&7: {msg}");
        SOCIAL_SPY_FORMAT = config.optString("social_spy_format", "{sender} -> {target}: {msg}");
        GLOBAL_FORMAT = config.optString("global_format", "&7[&6{server}&7] [&6{sender}&7]: &r{msg}");
        gcDefault = config.optBoolean("global_chat_default", false);
        chatCoolDowns = config.optBoolean("enable_chat_cooldown", true);
        spDefault = config.optBoolean("social_spy_default", false);
        chatCooldown = config.optLong("chat_cooldown", 10);
        SPAM_MESSAGE = config.optString("spam_message", "&7[&cUntamedChat&7] &cDon't spam the chat!");
        JSONObject commands = config.optJSONObject("commands");
        if (commands == null) {
            msgAliases = new String[] { "msg", "m" };
            replyAliases = new String[] { "reply", "r" };
            globalAliases = new String[] { "globalchat", "global", "g" };
            socialSpyAliases = new String[] { "socialspy", "sp", "spy" };
        } else {
            msgAliases = makeCommandArray(commands.optJSONArray("msg"), "msg", "m");
            replyAliases = makeCommandArray(commands.optJSONArray("reply"), "reply", "r");
            globalAliases = makeCommandArray(commands.optJSONArray("global_chat"), "globalchat", "global", "g");
            socialSpyAliases = makeCommandArray(commands.optJSONArray("social_spy"), "socialspy", "sp", "spy");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:net.arccotangent.pacchat.filesystem.KeyManager.java

@SuppressWarnings("ResultOfMethodCallIgnored")
public static void saveKeyByIP(String ip_address, PublicKey publicKey) {
    km_log.i("Saving public key for " + ip_address);
    X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(publicKey.getEncoded());
    File pubFile = new File(installationPath + File.separator + ip_address + ".pub");

    km_log.i("Deleting old key if it exists.");
    if (pubFile.exists())
        pubFile.delete();//from  w  ww . ja v  a2 s.  c om

    try {
        km_log.i(pubFile.createNewFile() ? "Creation of public key file successful."
                : "Creation of public key file failed!");

        FileOutputStream pubOut = new FileOutputStream(pubFile);
        pubOut.write(Base64.encodeBase64(pubSpec.getEncoded()));
        pubOut.flush();
        pubOut.close();

    } catch (IOException e) {
        km_log.e("Error while saving public key for " + ip_address + "!");
        e.printStackTrace();
    }
}

From source file:Main.java

public static void saveBitmapToFile(Bitmap bitmap, String _file) throws IOException {
    BufferedOutputStream os = null;
    try {/*w w w.j  a v  a 2 s  .  co  m*/
        File file = new File(_file);
        // String _filePath_file.replace(File.separatorChar +
        // file.getName(), "");
        int end = _file.lastIndexOf(File.separator);
        String _filePath = _file.substring(0, end);
        File filePath = new File(_filePath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        file.createNewFile();
        os = new BufferedOutputStream(new FileOutputStream(file));
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                Log.e("TAG_ERROR", e.getMessage(), e);
            }
        }
    }
}