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.mewin.util.Utils.java

public static File getLogFile(Plugin plugin) {
    File logFolder = new File(plugin.getDataFolder(), "logs");

    if (!logFolder.exists()) {
        logFolder.mkdirs();/*from  w  w  w.j  a  va 2 s.c  om*/
    }

    File logFile = new File(logFolder, sdf.format(new Date()) + ".log");

    if (!logFile.exists()) {
        try {
            logFile.createNewFile();
        } catch (IOException ex) {
            Bukkit.getLogger().log(Level.SEVERE, "Could not create log file for " + plugin.getName() + ": ",
                    ex);
            return null;
        }
    }

    return logFile;
}

From source file:de.decidr.ui.controller.VaadinTenantThemeInstaller.java

/**
 * Replaces a file with the given contents.
 * /*from  w w  w  .  ja  va2s.c om*/
 * @param toReplace
 *            file to replace
 * @param contents
 *            new contents for file
 * @throws IOException
 *             if some I/O error occurs.
 */
private static void replaceFile(File toReplace, InputStream contents) throws IOException {
    toReplace.delete();
    toReplace.createNewFile();
    FileOutputStream output = new FileOutputStream(toReplace);
    try {
        IOUtils.copy(contents, output);
    } finally {
        IOUtils.closeQuietly(output);
    }
}

From source file:com.l2jfree.gameserver.util.DatabaseBackupManager.java

public static void makeBackup() {
    File f = new File(Config.DATAPACK_ROOT, Config.DATABASE_BACKUP_SAVE_PATH);
    if (!f.mkdirs() && !f.exists()) {
        _log.warn("Could not create folder " + f.getAbsolutePath());
        return;/*from  ww  w . j  ava 2 s.c om*/
    }

    _log.info("DatabaseBackupManager: backing up `" + Config.DATABASE_BACKUP_DATABASE_NAME + "`...");

    Process run = null;
    try {
        run = Runtime.getRuntime().exec("mysqldump" + " --user=" + Config.DATABASE_LOGIN + " --password="
                + Config.DATABASE_PASSWORD
                + " --compact --complete-insert --default-character-set=utf8 --extended-insert --lock-tables --quick --skip-triggers "
                + Config.DATABASE_BACKUP_DATABASE_NAME, null, new File(Config.DATABASE_BACKUP_MYSQLDUMP_PATH));
    } catch (Exception e) {
    } finally {
        if (run == null) {
            _log.warn("Could not execute mysqldump!");
            return;
        }
    }

    try {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        Date time = new Date();

        File bf = new File(f, sdf.format(time) + (Config.DATABASE_BACKUP_COMPRESSION ? ".zip" : ".sql"));
        if (!bf.createNewFile())
            throw new IOException("Cannot create backup file: " + bf.getCanonicalPath());
        InputStream input = run.getInputStream();
        OutputStream out = new FileOutputStream(bf);
        if (Config.DATABASE_BACKUP_COMPRESSION) {
            ZipOutputStream dflt = new ZipOutputStream(out);
            dflt.setMethod(ZipOutputStream.DEFLATED);
            dflt.setLevel(Deflater.BEST_COMPRESSION);
            dflt.setComment("L2JFree Schema Backup Utility\r\n\r\nBackup date: "
                    + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS z").format(time));
            dflt.putNextEntry(new ZipEntry(Config.DATABASE_BACKUP_DATABASE_NAME + ".sql"));
            out = dflt;
        }

        byte[] buf = new byte[4096];
        int written = 0;
        for (int read; (read = input.read(buf)) != -1;) {
            out.write(buf, 0, read);

            written += read;
        }
        input.close();
        out.close();

        if (written == 0) {
            bf.delete();
            BufferedReader br = new BufferedReader(new InputStreamReader(run.getErrorStream()));
            String line;
            while ((line = br.readLine()) != null)
                _log.warn("DatabaseBackupManager: " + line);
            br.close();
        } else
            _log.info("DatabaseBackupManager: Schema `" + Config.DATABASE_BACKUP_DATABASE_NAME
                    + "` backed up successfully in " + (System.currentTimeMillis() - time.getTime()) / 1000
                    + " s.");

        run.waitFor();
    } catch (Exception e) {
        _log.warn("DatabaseBackupManager: Could not make backup: ", e);
    }
}

From source file:Main.java

public static String saveImg(Bitmap b, String name) throws Exception {
    String path = Environment.getExternalStorageDirectory().getPath() + File.separator + "QuCai/shareImg/";
    File mediaFile = new File(path + File.separator + name + ".jpg");
    if (mediaFile.exists()) {
        mediaFile.delete();//from ww w.  j a v  a2  s. c  om

    }
    if (!new File(path).exists()) {
        new File(path).mkdirs();
    }
    mediaFile.createNewFile();
    FileOutputStream fos = new FileOutputStream(mediaFile);
    b.compress(Bitmap.CompressFormat.PNG, 100, fos);
    fos.flush();
    fos.close();
    b.recycle();
    b = null;
    System.gc();
    return mediaFile.getPath();
}

From source file:brooklyn.util.io.FileUtil.java

public static void setFilePermissionsTo600(File file) throws IOException {
    file.createNewFile();
    file.setExecutable(false, false);//from w  w w  . ja  v a 2  s  .co m
    file.setReadable(false, false);
    file.setWritable(false, false);
    file.setReadable(true, true);
    file.setWritable(true, true);

    boolean setRead = file.setReadable(false, false) & file.setReadable(true, true);
    boolean setWrite = file.setWritable(false, false) & file.setWritable(true, true);
    boolean setExec = file.setExecutable(false, false);

    if (setRead && setWrite && setExec) {
        if (LOG.isTraceEnabled())
            LOG.trace("Set permissions to 600 for file {}", file.getAbsolutePath());
    } else {
        if (loggedSetFilePermissionsWarning) {
            if (LOG.isTraceEnabled())
                LOG.trace(
                        "Failed to set permissions to 600 for file {}: setRead={}, setWrite={}, setExecutable={}",
                        new Object[] { file.getAbsolutePath(), setRead, setWrite, setExec });
        } else {
            if (Os.isMicrosoftWindows()) {
                if (LOG.isDebugEnabled())
                    LOG.debug(
                            "Failed to set permissions to 600 for file {}; expected behaviour on Windows; setRead={}, setWrite={}, setExecutable={}; subsequent failures (on any file) will be logged at trace",
                            new Object[] { file.getAbsolutePath(), setRead, setWrite, setExec });
            } else {
                LOG.warn(
                        "Failed to set permissions to 600 for file {}: setRead={}, setWrite={}, setExecutable={}; subsequent failures (on any file) will be logged at trace",
                        new Object[] { file.getAbsolutePath(), setRead, setWrite, setExec });
            }
            loggedSetFilePermissionsWarning = true;
        }
    }
}

From source file:com.wavemaker.testsupport.UtilTest.java

public static String lockSemaphore(String semaphoreName, int iter, int sleep) throws Exception {

    String tmpdir = System.getProperty("java.io.tmpdir");
    File tempFile = new File(new File(tmpdir), semaphoreName + ".lock");

    int slept = 0;
    while (slept < iter) {
        if (!tempFile.exists()) {
            try {
                tempFile.createNewFile();
                tempFile.deleteOnExit();
                break;
            } catch (IOException e) {
                // ignore
            }/*ww  w.j  a  v a2  s  . c  om*/
        }

        Thread.sleep(sleep);
        slept++;
    }

    return tempFile.getAbsolutePath();
}

From source file:br.com.RatosDePC.Brpp.compiler.BrppCompiler.java

public static boolean compile(String path) {
    setFile(FileUtils.getBrinodirectory() + System.getProperty("file.separator") + "Arduino");
    setFile(getFile()/*from  w  ww.j ava 2  s  . c o  m*/
            .concat(path.substring(path.lastIndexOf(System.getProperty("file.separator")), path.length() - 5)));
    setFile(getFile()
            .concat(path.substring(path.lastIndexOf(System.getProperty("file.separator")), path.length() - 4)));
    setFile(getFile().concat("ino"));
    File ino = new File(getFile());
    if (!ino.exists()) {
        try {
            ino.getParentFile().mkdirs();
            ino.createNewFile();
        } catch (IOException e) {

        }
    }
    try {
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        String code = new String(encoded);
        JSONArray Keywords = JSONUtils.getKeywords();
        @SuppressWarnings("unchecked")
        Iterator<JSONObject> iterator = Keywords.iterator();
        while (iterator.hasNext()) {
            JSONObject key = iterator.next();
            String arg = (String) key.get("arg");
            if (arg.equals("false")) {
                code = code.replace((String) key.get("translate"), (String) key.get("arduino"));
            } else {
                code = code.replaceAll((String) key.get("translate"), (String) key.get("arduino"));
            }
        }

        try (FileWriter file = new FileWriter(getFile())) {
            file.write(code);
        }
        System.out.println(code);
        return true;

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;

}

From source file:Main.java

public static void put(String s, String name) {
    try {//from w w  w  . j a va2 s  .c  om
        File saveFile = new File(Environment.getExternalStorageDirectory() + "/hhtlog/" + name + ".txt");
        if (!saveFile.exists()) {
            File dir = new File(saveFile.getParent());
            dir.mkdirs();
            saveFile.createNewFile();
        }

        FileOutputStream outStream = new FileOutputStream(saveFile);
        outStream.write(s.getBytes());
        outStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.arcusys.liferay.vaadinplugin.util.WidgetsetUtil.java

/**
 * Creates a widgetset .gwt.xml file under a given directory.
 *
 * @param widgetset/*from  www .j  a v  a 2s  .c  o m*/
 *            the name of Widgetset. For example: com.example.TestWidgetSet
 * @throws java.io.IOException
 */
public static void createWidgetset(File tmpDir, String widgetset, Set<String> includeWidgetsets)
        throws IOException {

    String dir = widgetset.substring(0, widgetset.lastIndexOf(".")).replace(".",
            ControlPanelPortletUtil.FileSeparator);
    String file = widgetset.substring(widgetset.lastIndexOf(".") + 1, widgetset.length()) + ".gwt.xml";

    File widgetsetDir = new File(tmpDir, dir);
    if (!widgetsetDir.mkdirs()) {
        throw new IOException("Could not create dir: " + widgetsetDir.getAbsolutePath());
    }
    File widgetsetFile = new File(widgetsetDir, file);
    if (!widgetsetFile.createNewFile()) {
        throw new IOException("");
    }

    PrintStream printStream = new PrintStream(new FileOutputStream(widgetsetFile));
    printStream.print("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<!DOCTYPE module PUBLIC \"-//Google Inc.//DTD "
            + "Google Web Toolkit 1.7.0//EN\" \"http://google"
            + "-web-toolkit.googlecode.com/svn/tags/1.7.0/dis" + "tro-source/core/src/gwt-module.dtd\">\n");
    printStream.print("<module>\n");

    for (String ws : includeWidgetsets) {
        printStream.print("<inherits name=\"" + ws + "\" />\n");
    }

    printStream.print("\n</module>\n");
    printStream.close();
}

From source file:fr.ece.epp.tools.Utils.java

public static void writeScript(String path, String version) {
    String system = System.getProperty("os.name");
    try {//from w w  w  .j a  v a 2  s .  c  om
        if (system.startsWith("Windows")) {
            File writename = new File(path);
            writename.createNewFile();

            BufferedWriter out = new BufferedWriter(new FileWriter(writename));

            out.write("%~d0\n\r");
            out.write("cd %~dp0\n\r");
            out.write("mvn install -P base," + version);
            out.flush(); // 
            out.close(); // ?  

        } else if (system.startsWith("Linux") || system.startsWith("Mac")) {
            File writename = new File(path);
            writename.createNewFile();

            BufferedWriter out = new BufferedWriter(new FileWriter(writename));

            out.write("#!/bin/sh\n\n");
            out.write("BASEDIR=$(dirname $0)\n");
            out.write("cd $BASEDIR\n");
            out.write("mvn install -P base," + version);
            out.flush(); // 
            out.close(); // ?  
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}