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.plotsquared.iserver.util.FileUtils.java

/**
 * Add files to a zip file//  w w w  . j  a  v  a2  s . c  o m
 *
 * @param zipFile Zip File
 * @param files   Files to add to the zip
 * @param delete  If the original files should be deleted
 * @throws Exception If anything goes wrong
 */
public static void addToZip(final File zipFile, final File[] files, final boolean delete) throws Exception {
    Assert.notNull(zipFile, files);

    if (!zipFile.exists()) {
        if (!zipFile.createNewFile()) {
            throw new RuntimeException("Couldn't create " + zipFile);
        }
    }

    final File temporary = File.createTempFile(zipFile.getName(), "");
    //noinspection ResultOfMethodCallIgnored
    temporary.delete();

    if (!zipFile.renameTo(temporary)) {
        throw new RuntimeException("Couldn't rename " + zipFile + " to " + temporary);
    }

    final byte[] buffer = new byte[1024 * 16]; // 16mb

    ZipInputStream zis = new ZipInputStream(new FileInputStream(temporary));
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));

    ZipEntry e = zis.getNextEntry();
    while (e != null) {
        String n = e.getName();

        boolean no = true;
        for (File f : files) {
            if (f.getName().equals(n)) {
                no = false;
                break;
            }
        }

        if (no) {
            zos.putNextEntry(new ZipEntry(n));
            int len;
            while ((len = zis.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
        }
        e = zis.getNextEntry();
    }
    zis.close();
    for (File file : files) {
        InputStream in = new FileInputStream(file);
        zos.putNextEntry(new ZipEntry(file.getName()));

        int len;
        while ((len = in.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
        }

        zos.closeEntry();
        in.close();
    }
    zos.close();
    temporary.delete();

    if (delete) {
        for (File f : files) {
            f.delete();
        }
    }
}

From source file:eu.europa.ejusticeportal.dss.applet.model.service.FileSeekerTest.java

@BeforeClass
public static void setUpTestFileStructure() throws IOException, InterruptedException {

    assertTrue(s != null && s.length() != 0);
    assertTrue(home.exists());// www. j  av  a  2 s .c  om
    File testFileStructure = new File(home, "dss_applet_test/aaa/bb bb/cc ccc/ddd dd");

    if (testFileStructure.exists()) {
        FileUtils.deleteDirectory(testFileStructure);
    }
    testFileStructure = new File(home, "dss_applet_test/aaa/bb bb/cc ccc/ddd dd");
    if (!testFileStructure.exists()) {
        testFileStructure.mkdirs();
    }
    assertTrue(testFileStructure.exists());
    File library = new File(testFileStructure, "library.dll");
    if (!library.exists()) {
        library.createNewFile();
    }
    assertTrue(library.exists());

    File library2Folder = new File(home, "dss_applet_test/aaa");
    File library2 = new File(library2Folder, "pkcs11.so");
    if (!library2.exists()) {
        library2.createNewFile();
    }
    assertTrue(library2.exists());

    File library3Folder = new File(home, "dss_applet_test/aaa/bb bb/cc ccc");
    File library3 = new File(library3Folder, "pkcs11.so");
    if (!library3.exists()) {
        library3.createNewFile();
    }
    assertTrue(library3.exists());

    try {
        //Show the directory structure we created
        ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "tree", "/a", "/F",
                new File(home, "dss_applet_test").getAbsolutePath());

        Process p = pb.start();
        InputStreamReader isr = new InputStreamReader(p.getInputStream(), Charset.forName("US-ASCII"));
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
            log(line);
        }
    } catch (Exception e) {
        log(e.getMessage());
    }
}

From source file:org.jboss.as.test.integration.security.loginmodules.common.Utils.java

public static synchronized void logToFile(String what, String where) {
    try {/*from www  . j  a v a2 s.  co m*/
        File file = new File(where);
        if (!file.exists()) {
            file.createNewFile();
        }
        OutputStream os = new FileOutputStream(file, true);
        Writer writer = new OutputStreamWriter(os);
        writer.write(what);
        if (!what.endsWith("\n")) {
            writer.write("\n");
        }
        writer.close();
        os.close();

    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:main.TestManager.java

/**
 * Deletes all local tests, downloads tests from the server
 * and saves all downloaded test in the local directory.
 */// ww w .  j  a  v  a 2 s  .  c  o  m
public static void syncTestsWithServer() {
    FTPClient ftp = new FTPClient();
    boolean error = false;
    try {
        int reply;
        String server = "zajicek.endora.cz";
        ftp.connect(server, 21);

        // After connection attempt, we check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        //Not connected successfully - inform the user
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            Debugger.println("FTP server refused connection.");
            ErrorInformer.failedSyncing();
            return;
        }
        // LOGIN
        boolean success = ftp.login("plakato", "L13nK4");
        Debugger.println("Login successful: " + success);
        if (success == false) {
            ftp.disconnect();
            ErrorInformer.failedSyncing();
            return;
        }
        ftp.enterLocalPassiveMode();
        // Get all files from the server
        FTPFile[] files = ftp.listFiles();
        System.out.println("Got files! Count: " + files.length);
        // Delete all current test to be replaced with 
        // actulized version
        File[] locals = new File("src/tests/").listFiles();
        for (File f : locals) {
            if (f.getName() == "." || f.getName() == "..") {
                continue;
            }
            f.delete();
        }
        // Copy the files from server to local folder
        int failed = 0;
        for (FTPFile f : files) {
            if (f.isFile()) {
                Debugger.println(f.getName());
                if (f.getName() == "." || f.getName() == "..") {
                    continue;
                }
                File file = new File("src/tests/" + f.getName());
                file.createNewFile();
                OutputStream output = new FileOutputStream(file);
                if (!ftp.retrieveFile(f.getName(), output))
                    failed++;
                output.close();
            }
        }
        // If we failed to download some file, inform the user
        if (failed != 0) {
            ftp.disconnect();
            ErrorInformer.failedSyncing();
            return;
        }
        // Disconnect ftp client or resolve the potential error
        ftp.logout();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                // do nothing
            }
        }
    }
    if (error) {
        ErrorInformer.failedSyncing();

    }
    Alert alert = new Alert(AlertType.INFORMATION);
    alert.setTitle("Download hotov");
    alert.setHeaderText(null);
    alert.setContentText("Vetky testy boli zo servru spene stiahnut.");

    alert.showAndWait();
    alert.close();
}

From source file:com.flexive.core.storage.binary.FxBinaryUtils.java

/**
 * Create a new binary transit file for the given division and handle
 *
 * @param divisionId division//from   ww w.j  ava  2s  . co  m
 * @param handle     binary handle
 * @param ttl        time to live (will be part of the filename)
 * @return transit file
 * @throws IOException on errors
 */
public static File createTransitFile(int divisionId, String handle, long ttl) throws IOException {
    File baseDir = new File(getTransitDirectory() + File.separatorChar + String.valueOf(divisionId));
    if (!baseDir.exists())
        if (!baseDir.mkdirs())
            throw new IOException("Failed to create directory " + baseDir.getAbsolutePath());
    File result = new File(
            baseDir.getAbsolutePath() + File.separatorChar + handle + "__" + String.valueOf(ttl) + TRANSIT_EXT);
    if (!result.createNewFile())
        throw new IOException("Failed to create file " + result.getAbsolutePath());
    return result;
}

From source file:ModelParse.java

public static void parseProtocol(JSONObject protocolObject, String keyName, String folderPath,
        String packageName) throws IOException, JSONException {
    keyName = keyName.replaceAll("-", "_");
    Iterator<String> keys = protocolObject.keys();

    if (null != keyName && keyName.length() > 0) {
        String parentClass = null;
        String keyArray[] = keyName.split("<");
        if (keyArray.length > 1) {
            keyName = keyArray[0];//from   w w w  .  j a v a2  s .co  m
            parentClass = keyArray[1];
        }

        keyName = keyName.trim();
        File file = new File(folderPath + "/output/" + keyName + ".java");
        file.createNewFile();
        FileOutputStream out = new FileOutputStream(file, true);

        StringBuffer sb = new StringBuffer();
        sb.append("\n");
        sb.append("package " + packageName + ";");
        sb.append("\n");
        sb.append("import java.util.ArrayList;\n" + "import org.json.JSONArray;\n"
                + "import org.json.JSONException;\n" + "import org.json.JSONObject;\n"
                + "import com.external.activeandroid.Model;\n"
                + "import com.external.activeandroid.DataBaseModel;\n"
                + "import com.external.activeandroid.annotation.Column;\n"
                + "import com.external.activeandroid.annotation.Table;\n");
        sb.append("\n");
        sb.append("@Table(name = \"" + keyName + "\")");
        sb.append("\n");
        if (null == parentClass) {
            sb.append("public class " + keyName + "  extends DataBaseModel\n{\n");
        } else {
            sb.append("public class " + keyName + "   extends " + parentClass + "\n{\n");
        }

        while (keys.hasNext()) {
            String key = keys.next();
            Object item = protocolObject.get(key);

            String column_name = "";
            boolean is_unique = false;

            String key_raw_name = key;

            if (key_raw_name.startsWith("! ")) {
                is_unique = true;
                key_raw_name = key_raw_name.replaceAll("! ", "");
            }

            if (0 == key_raw_name.toLowerCase().compareTo("id")) {
                column_name = keyName + "_id";
            } else {
                column_name = key_raw_name;
            }

            if (item.getClass() == JSONObject.class) {
                parseProtocol((JSONObject) item, key, folderPath, packageName);
            } else if (item.getClass() == String.class) {
                item = ((String) item).trim();
                if (((String) item).startsWith("{") && ((String) item).endsWith("}")) {
                    sb.append("\n");
                    sb.append("     @Column(name = \"" + column_name + "\")");
                    sb.append("\n");

                    String className = new String((String) item);
                    className = className.trim();
                    className = className.replace("{", "");
                    className = className.replace("}", "");
                    sb.append("     public " + className + "   " + key_raw_name + ";\n");
                } else if (((String) item).startsWith("<") && ((String) item).endsWith(">")) {
                    sb.append("\n");
                    if (is_unique) {
                        sb.append("     @Column(name = \"" + column_name + "\",unique = true)");
                    } else {
                        sb.append("     @Column(name = \"" + column_name + "\")");
                    }

                    sb.append("\n");
                    sb.append("     public int " + key_raw_name + ";\n");

                } else {
                    sb.append("\n");
                    sb.append("     @Column(name = \"" + column_name + "\")");
                    sb.append("\n");
                    sb.append("     public String" + "   " + key_raw_name + ";\n");
                }
            } else if (item.getClass() == Integer.class) {

                sb.append("\n");
                if (is_unique) {
                    sb.append("     @Column(name = \"" + column_name + "\",unique = true)");
                } else {
                    sb.append("     @Column(name = \"" + column_name + "\")");
                }

                sb.append("\n");
                sb.append("     public int " + key_raw_name + ";\n");

            } else if (item.getClass() == Double.class) {
                sb.append("\n");
                sb.append("     @Column(name = \"" + column_name + "\")");
                sb.append("\n");
                sb.append("     public double" + "   " + key_raw_name + ";\n");
            } else if (item.getClass() == Float.class) {
                sb.append("\n");
                sb.append("     @Column(name = \"" + column_name + "\")");
                sb.append("\n");
                sb.append("     public float" + "   " + key_raw_name + ";\n");
            }

            else if (item.getClass() == Boolean.class) {

                sb.append("\n");
                if (is_unique) {
                    sb.append("     @Column(name = \"" + column_name + "\",unique = true)");
                } else {
                    sb.append("     @Column(name = \"" + column_name + "\")");
                }

                sb.append("\n");
                sb.append("     public boolean " + key_raw_name + ";\n");

            } else if (item.getClass() == JSONArray.class) {
                JSONArray itemJSONArray = (JSONArray) item;
                if (itemJSONArray.length() > 0) {

                    Object subItem = itemJSONArray.opt(0);
                    String className = "";

                    if (subItem.getClass() == String.class) {
                        if (((String) subItem).startsWith("{")) {
                            className = new String((String) subItem);
                        } else {
                            className = "String";
                        }

                    } else if (subItem.getClass() == Integer.class) {
                        className = "Integer";
                    }

                    className = className.replace("[", "");
                    className = className.replace("]", "");
                    className = className.trim();

                    className = className.replace("{", "");
                    className = className.replace("}", "");
                    sb.append("\n");
                    sb.append("     public ArrayList<" + className + ">   " + key_raw_name + " = new ArrayList<"
                            + className + ">();\n");
                }
            }
        }

        //add fromJson method
        sb = Utils.addfromJson(protocolObject, keyName, sb, parentClass);
        sb = Utils.addtoJson(protocolObject, keyName, sb, parentClass);

        sb.append("\n}\n");

        out.write(sb.toString().getBytes("utf-8"));
        out.close();
    } else {
        while (keys.hasNext()) {
            String key = keys.next();
            Object item = protocolObject.get(key);
            if (item.getClass() == JSONObject.class) {
                parseProtocol((JSONObject) item, key, folderPath, packageName);
            }
        }
    }
}

From source file:de.dakror.villagedefense.util.SaveHandler.java

public static void saveGame() {
    try {/*from  ww w  .j  a v a 2s .c o m*/
        File save = new File(CFG.DIR, "saves/"
                + new SimpleDateFormat("'Spielstand' dd.MM.yyyy HH-mm-ss").format(new Date()) + ".save");
        save.createNewFile();

        JSONObject o = new JSONObject();

        o.put("version", CFG.VERSION);
        o.put("created", Game.currentGame.worldCreated);
        o.put("width", Game.world.width);
        o.put("height", Game.world.height);
        o.put("tile", new BASE64Encoder().encode(Compressor.compressRow(Game.world.getData())));
        o.put("resources", Game.currentGame.resources.getData());
        o.put("researches", Game.currentGame.researches);
        o.put("wave", WaveManager.wave);
        o.put("time", WaveManager.nextWave);

        JSONArray entities = new JSONArray();
        for (Entity e : Game.world.entities) {
            if ((e instanceof Forester) || (e instanceof Woodsman))
                continue; // don't save them, because they get spawned by the house upgrades

            entities.put(e.getData());
        }
        o.put("entities", entities);

        Compressor.compressFile(save, o.toString());
        //         Helper.setFileContent(new File(save.getPath() + ".debug"), o.toString());
        Game.currentGame.state = 3;
        JOptionPane.showMessageDialog(Game.w, "Spielstand erfolgreich gespeichert.", "Speichern erfolgreich",
                JOptionPane.INFORMATION_MESSAGE);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.naonedbus.utils.InfoDialogUtils.java

/**
 * Afficher une dialog avec un message, uniquement si elle n'a pas dj t
 * affiche// w  ww.  j  av  a2 s  .c o m
 * 
 * @param context
 * @param messageId
 */
public static void showIfNecessary(final Context context, final int titreId, final int messageId) {
    final File dataFile = new File(context.getFilesDir(), MESSAGE_FOLDER + File.separator + messageId);

    createDir(context);
    if (!dataFile.exists()) {
        show(context, titreId, messageId);
        try {
            dataFile.createNewFile();
        } catch (final IOException e) {
            BugSenseHandler.sendExceptionMessage("Erreur lors de la cration du marqueur", null, e);
        }
    }
}

From source file:ai.susi.json.JsonFile.java

/**
 * write a json file in transaction style: first write a temporary file,
 * then rename the original file to another temporary file, then rename the
 * just written file to the target file name, then delete all other temporary files.
 * @param file// w  w w.  j  a v  a  2 s.  c om
 * @param json
 * @throws IOException
 */
public static void writeJson(File file, JSONObject json) throws IOException {
    if (file == null)
        throw new IOException("file must not be null");
    if (json == null)
        throw new IOException("json must not be null");
    if (!file.exists())
        file.createNewFile();
    File tmpFile0 = new File(file.getParentFile(), file.getName() + "." + System.currentTimeMillis());
    File tmpFile1 = new File(tmpFile0.getParentFile(), tmpFile0.getName() + "1");
    FileWriter writer = new FileWriter(tmpFile0);
    writer.write(json.toString(2));
    writer.close();
    file.renameTo(tmpFile1);
    tmpFile0.renameTo(file);
    tmpFile1.delete();
}

From source file:com.hybris.datahub.outbound.utils.CommonUtils.java

/**
 * @param filePath//w  w  w  . ja v  a 2  s  .c om
 * @param suffix
 * @param content
 */
public static void writeFile(final String filePath, String suffix, final String content) {

    suffix = StringUtils.isEmpty(suffix) ? "json" : suffix;

    final File file = new File(filePath + "." + suffix);
    FileOutputStream out = null;
    try {
        if (!file.exists()) {
            file.createNewFile();
        } else {
            file.delete();
            file.createNewFile();
        }
        out = new FileOutputStream(file, true);
        out.write(content.getBytes("utf-8"));
    } catch (final UnsupportedEncodingException e) {
        LOGGER.error(e.getMessage());
    } catch (final FileNotFoundException e) {
        LOGGER.error(e.getMessage());
    } catch (final IOException e) {
        LOGGER.error(e.getMessage());
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (final IOException e) {
                LOGGER.error(e.getMessage());
            }
        }
    }
}