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.hmiard.blackwater.projects.Builder.java

/**
 * Appending a new server to a project./*from  w  w  w.  j a va2s . c o m*/
 *
 * @param projectRoot String
 * @param serverName String
 * @param consoleListener ConsoleEmulator
 * @param needsDb Boolean
 */
public static Boolean appendServer(String projectRoot, String serverName, ConsoleEmulator consoleListener,
        Boolean needsDb) {

    try {
        serverName = serverName.substring(0, 1).toUpperCase() + serverName.substring(1).toLowerCase();
        String shortServerName = serverName;
        serverName += "Server";
        String src = projectRoot + "\\src\\" + serverName;
        File checker = new File(projectRoot + "\\src\\" + serverName);
        File composerJSON = new File(projectRoot + "\\composer.json");

        if (checker.exists() && checker.isDirectory()) {
            consoleListener.push("This server already exists ! Operation aborted.");
            return false;
        }
        if (!composerJSON.exists()) {
            consoleListener.push("File composer.json is missing ! Operation aborted.");
            return false;
        }

        if (needsDb)
            copyFolder(new File("resources/packages/DefaultApp"), new File(src));
        else
            copyFolder(new File("resources/packages/NoDbApp"), new File(src));

        FileOutputStream writer;
        File core = new File(src + "\\BlackwaterDefaultApp.php");
        File qf = new File(src + "\\DefaultAppQueryFactory.php");
        File bootstrap = new File(src + "\\bin\\init.php");

        String coreContent = readFile(core.getAbsolutePath());
        coreContent = coreContent.replace("BlackwaterDefaultApp", serverName);
        File newCore = new File(src + "\\" + serverName + ".php");
        if (newCore.createNewFile() && core.delete()) {
            writer = new FileOutputStream(newCore);
            writer.write(coreContent.getBytes());
            writer.flush();
            writer.close();
        }

        if (needsDb) {
            String qfContent = readFile(qf.getAbsolutePath());
            qfContent = qfContent.replace("BlackwaterDefaultApp", serverName);
            qfContent = qfContent.replace("DefaultApp", shortServerName);
            File newQf = new File(src + "\\" + shortServerName + "QueryFactory.php");
            if (newQf.createNewFile() && qf.delete()) {
                writer = new FileOutputStream(newQf);
                writer.write(qfContent.getBytes());
                writer.flush();
                writer.close();
            }
        }

        String bootsrapContent = readFile(bootstrap.getAbsolutePath());
        Random r = new Random();
        bootsrapContent = bootsrapContent.replace("Default", shortServerName);
        bootsrapContent = bootsrapContent.replace("8080", String.valueOf(r.nextInt(2000) + 7000));
        writer = new FileOutputStream(bootstrap);
        writer.write(bootsrapContent.getBytes());
        writer.flush();
        writer.close();

        JSONObject composer = new JSONObject(readFile(composerJSON.getAbsolutePath()));
        JSONObject autoload = composer.getJSONObject("autoload");
        JSONObject psr0 = autoload.getJSONObject("psr-0");
        psr0.put(serverName, "src");

        BufferedWriter cw = new BufferedWriter(new FileWriter(composerJSON.getAbsoluteFile()));
        String content = composer.toString(4).replaceAll("\\\\", "");
        cw.write(content);
        cw.close();

        consoleListener.push(serverName + " created !\n");

    } catch (JSONException | IOException e) {
        e.printStackTrace();
    }

    return true;
}

From source file:bzstats.chart.AbstractChartFactory.java

/**
 * Utility function to save an image as a PNG file.
 *
 * @param image/*from   w ww  .j  av a2  s  .  c  om*/
 *            The image to save.
 * @param filename
 *            The filename to save the image as.
 * @throws BZStatsException
 *             If the file could not be written.
 */
public static final void savePNGImage(BufferedImage image, String filename) throws BzStatsException {

    File outputfile = new File(filename);

    // overwrite
    if (outputfile.exists()) {
        if (outputfile.canWrite()) {
            outputfile.delete();
        } else {
            throw new BzStatsException("Cannot overwrite " + filename);
        }
    }

    boolean filecreated;
    try {
        filecreated = outputfile.createNewFile();
    } catch (IOException e2) {
        throw new BzStatsException("Failed to create file " + filename);
    }

    if (filecreated) {

        OutputStream out = null;
        try {
            out = new FileOutputStream(outputfile);
        } catch (FileNotFoundException e3) {
            throw new BzStatsException("Failed to write to file " + filename);
        }

        SunPNGEncoderAdapter encoder = new SunPNGEncoderAdapter();

        try {
            encoder.encode(image, out);
        } catch (IOException e) {
            throw new BzStatsException("Failed to encode file " + filename);
        } finally {
            try {
                out.close();
            } catch (IOException e1) {
                throw new BzStatsException("Failed to close file " + filename);
            }
        }
    } else {
        throw new BzStatsException("Failed to create file " + filename);
    }

}

From source file:com.knockturnmc.api.util.ConfigurationUtils.java

/**
 * Loads a plain file./*ww w  . j a va  2  s  .c  o m*/
 * If the desired file is not found, a file with the same name will be copied from the classpath to the datafolder.
 * If no default file was found in the classloader's classpath, an empty file will be created.
 *
 * @param classLoader the classloader to use for the default file
 * @param file        the filename to create/load
 * @param datafolder  the datafolder to use
 * @return the loaded/created file
 * @throws IOException if something went wrong
 */
public static File getConfigFile(ClassLoader classLoader, String file, File datafolder) throws IOException {
    File config = new File(datafolder, file);
    datafolder.mkdirs();
    if (!config.exists()) {
        logger.info("No configuration file found. Copying default configuration...");
        try (InputStream in = classLoader.getResourceAsStream(file)) {
            if (in != null) {
                if (!config.createNewFile()) {
                    logger.error("Failed creating default file.");
                    throw new RuntimeException("Failed to create default file");
                }
                try (OutputStream out = new FileOutputStream(config)) {
                    IOUtils.copy(in, out);
                    out.flush();
                }
            } else {
                config.createNewFile();
            }
        }
    }
    return config;
}

From source file:com.android.emailcommon.utility.AttachmentUtilities.java

/**
 * Save the attachment to its final resting place (cache or sd card)
 *///from   w ww  .  j ava 2 s  .co m
public static void saveAttachment(Context context, InputStream in, Attachment attachment) {
    Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    ContentValues cv = new ContentValues();
    long attachmentId = attachment.mId;
    long accountId = attachment.mAccountKey;
    String contentUri;
    long size;
    try {
        if (attachment.mUiDestination == UIProvider.AttachmentDestination.CACHE) {
            File saveIn = getAttachmentDirectory(context, accountId);
            if (!saveIn.exists()) {
                saveIn.mkdirs();
            }
            File file = getAttachmentFilename(context, accountId, attachmentId);
            file.createNewFile();
            size = copyFile(in, file);
            contentUri = getAttachmentUri(accountId, attachmentId).toString();
        } else if (Utility.isExternalStorageMounted()) {
            File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            size = copyFile(in, file);
            String absolutePath = file.getAbsolutePath();

            // Although the download manager can scan media files, scanning only happens
            // after the user clicks on the item in the Downloads app. So, we run the
            // attachment through the media scanner ourselves so it gets added to
            // gallery / music immediately.
            MediaScannerConnection.scanFile(context, new String[] { absolutePath }, null, null);

            DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                    false /* do not use media scanner */, attachment.mMimeType, absolutePath, size,
                    true /* show notification */);
            contentUri = dm.getUriForDownloadedFile(id).toString();

        } else {
            Log.w(Logging.LOG_TAG, "Trying to save an attachment without external storage?");
            throw new IOException();
        }

        // Update the attachment
        cv.put(AttachmentColumns.SIZE, size);
        cv.put(AttachmentColumns.CONTENT_URI, contentUri);
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.SAVED);
    } catch (IOException e) {
        // Handle failures here...
        cv.put(AttachmentColumns.UI_STATE, UIProvider.AttachmentState.FAILED);
    }
    context.getContentResolver().update(uri, cv, null, null);

}

From source file:com.thoughtworks.go.util.FileUtil.java

public static void createFilesByPath(File baseDir, String... files) throws IOException {
    for (String file : files) {
        if (file.endsWith("/")) {
            File file1 = new File(baseDir, file);
            file1.mkdirs();/*from   www  .  j  a v  a  2  s . c om*/
        } else {
            File file1 = new File(baseDir, file);
            file1.getParentFile().mkdirs();
            file1.createNewFile();
        }
    }
}

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

public static void saveContentsToFile(String content, File f) throws IOException {
    if (!f.exists()) {
        f.createNewFile();/*www. j  a v  a  2s  . c  o  m*/
    }

    BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(f, false));

    bufferedWriter.write(content);
    bufferedWriter.flush();
    bufferedWriter.close();
}

From source file:Main.java

private static boolean moveFile(File oldPlace, File newPlace, boolean removeOld) {
    boolean removeNewFile = true;
    Log.i("cr3", "Moving file " + oldPlace.getAbsolutePath() + " to " + newPlace.getAbsolutePath());
    if (!oldPlace.exists()) {
        Log.i("cr3", "File " + oldPlace.getAbsolutePath() + " does not exist!");
        return false;
    }/*from   w w w . ja  va2s.  c  om*/
    FileOutputStream os = null;
    FileInputStream is = null;
    try {
        if (!newPlace.createNewFile())
            return false; // cannot create file
        os = new FileOutputStream(newPlace);
        is = new FileInputStream(oldPlace);
        byte[] buf = new byte[0x10000];
        for (;;) {
            int bytesRead = is.read(buf);
            if (bytesRead <= 0)
                break;
            os.write(buf, 0, bytesRead);
        }
        removeNewFile = false;
        oldPlace.delete();
        return true;
    } catch (IOException e) {
        return false;
    } finally {
        try {
            if (os != null)
                os.close();
        } catch (IOException ee) {
            // ignore
        }
        try {
            if (is != null)
                is.close();
        } catch (IOException ee) {
            // ignore
        }
        if (removeNewFile)
            newPlace.delete();
    }
}

From source file:net.orpiske.sdm.lib.net.Downloader.java

/**
 * Setups the output file/* ww  w.jav a  2s  . c om*/
 * @param url file URL
 * @param overwrite whether to overwrite existent files
 * @return A new File object pointing to the output file
 * @throws MalformedURLException
 * @throws URISyntaxException
 * @throws IOException if unable to create the output directory, file or remove an
 * existent file
 */
private static File setupOutputFile(String url, boolean overwrite)
        throws MalformedURLException, URISyntaxException, IOException {
    String fileName = URLUtils.getFilename(url);
    String workDir = WorkdirUtils.getWorkDir();
    String fullName = workDir + File.separator + fileName;

    File outputFile = new File(fullName);

    if (!outputFile.getParentFile().exists()) {
        if (!outputFile.getParentFile().mkdirs()) {
            throw new IOException("Unable to create output directory " + fullName);
        }
    }

    if (!outputFile.exists()) {
        if (!outputFile.createNewFile()) {
            throw new IOException("Unable to create file " + fullName);
        }
    } else {
        if (overwrite) {
            if (outputFile.delete()) {
                if (!outputFile.createNewFile()) {
                    throw new IOException("Unable to create file " + fullName);
                }
            } else {
                throw new IOException("Unable to delete existing file " + fullName);
            }
        } else {
            logger.info("Destination file " + fullName + " already exists");
        }
    }
    return outputFile;
}

From source file:Main.java

/** Writes a copy of a file.
 * // w  w w . j a v  a 2 s. c  o m
 * @param src the file to copy
 * @param dst the location to write the new file
 * @throws IOException
 */
public synchronized static void copy(File src, File dst) throws IOException {
    if (b1 == null)
        b1 = new byte[4096];

    FileInputStream in = null;
    FileOutputStream out = null;
    try {
        in = new FileInputStream(src);
        dst.getParentFile().mkdirs();
        dst.createNewFile();
        out = new FileOutputStream(dst);
        int k = in.read(b1);
        while (k != -1) {
            out.write(b1, 0, k);
            k = in.read(b1);
        }
    } finally {
        try {
            in.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
        try {
            out.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

From source file:com.hypersocket.i18n.I18N.java

public static void flushOverrides() {

    for (File f : overideProperties.keySet()) {
        try {/*from  w ww .  j  av  a  2  s. c  o  m*/
            Properties properties = overideProperties.get(f);
            f.getParentFile().mkdirs();
            f.createNewFile();
            FileOutputStream out = new FileOutputStream(f);
            try {
                properties.store(out, "Hypersocket message bundle override file");
            } finally {
                FileUtils.closeQuietly(out);
            }
        } catch (IOException e) {
            log.error("Failed to flush override file " + f.getName(), e);
        }
    }
}