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:Main.java

private static void fileUnZip(ZipInputStream zis, File file) throws FileNotFoundException, IOException {
    java.util.zip.ZipEntry zip = null;
    while ((zip = zis.getNextEntry()) != null) {
        String name = zip.getName();
        File f = new File(file.getAbsolutePath() + File.separator + name);
        if (zip.isDirectory()) {
            f.mkdirs();//from  ww w .  j a  v  a2s  .c o m
        } else {
            f.getParentFile().mkdirs();
            f.createNewFile();
            BufferedOutputStream bos = null;
            try {
                bos = new BufferedOutputStream(new FileOutputStream(f));
                byte b[] = new byte[2048];
                int aa = 0;
                while ((aa = zis.read(b)) != -1) {
                    bos.write(b, 0, aa);
                }
                bos.flush();
            } finally {
                bos.close();
            }
            bos.close();
        }
    }

}

From source file:com.photon.phresco.util.FileUtil.java

public static File writeFileFromInputStream(InputStream inputStream, String tempZip) throws PhrescoException {
    File tempZipFile = new File(tempZip);
    try {// www  .j a va 2  s.co  m
        if (!tempZipFile.exists()) {
            tempZipFile.createNewFile();
        }
        OutputStream out = new FileOutputStream(new File(tempZip));
        int read = 0;
        byte[] bytes = new byte[BUFFER_SIZE];
        while ((read = inputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        inputStream.close();
        out.flush();
        out.close();
    } catch (Exception e) {
        throw new PhrescoException(e);
    }

    return tempZipFile;
}

From source file:edu.isi.webserver.FileUtil.java

public static void copyFiles(File destination, File source) throws FileNotFoundException, IOException {
    if (!destination.exists())
        destination.createNewFile();
    InputStream in = new FileInputStream(source);
    OutputStream out = new FileOutputStream(destination);

    byte[] buf = new byte[1024];
    int len;/*w w  w .  j av a2 s.  co m*/

    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
    logger.debug("Done copying contents of " + source.getName() + " to " + destination.getName());
}

From source file:amazonechoapi.AmazonEchoApi.java

private static boolean checkItemId(String itemId) throws IOException {
    File file = new File("Items.txt");
    boolean ret = false;
    try {//from   w  w  w.j  a va  2s.c o  m
        if (!file.exists()) {
            file.createNewFile();
        }
        Scanner scanner = new Scanner(file);
        int lineNum = 0;
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            lineNum++;
            if (line.contains(itemId)) {
                ret = true;
            }
        }
    } catch (Exception e) {
        ret = false;
    }
    return ret;
}

From source file:Main.java

public static boolean isExternalStorageWriteable() {
    boolean writealbe = false;
    long start = System.currentTimeMillis();
    if (TextUtils.equals(Environment.MEDIA_MOUNTED, Environment.getExternalStorageState())) {
        File esd = Environment.getExternalStorageDirectory();
        if (esd.exists() && esd.canWrite()) {
            File file = new File(esd, ".696E5309-E4A7-27C0-A787-0B2CEBF1F1AB");
            if (file.exists()) {
                writealbe = true;/*from   w w  w.  jav  a  2s  .co m*/
            } else {
                try {
                    writealbe = file.createNewFile();
                } catch (IOException e) {
                    Log.w(TAG, "isExternalStorageWriteable() can't create test file.");
                }
            }
        }
    }
    long end = System.currentTimeMillis();
    Log.i(TAG, "Utility.isExternalStorageWriteable(" + writealbe + ") cost " + (end - start) + "ms.");
    return writealbe;
}

From source file:com.cloud.utils.ProcessUtil.java

public static void pidCheck(String pidDir, String run) throws ConfigurationException {

    String dir = pidDir == null ? "/var/run" : pidDir;

    try {/*from w  w  w  .  j a  v a2 s  . c o  m*/
        final File propsFile = PropertiesUtil.findConfigFile("environment.properties");
        if (propsFile == null) {
            s_logger.debug("environment.properties could not be opened");
        } else {
            final Properties props = PropertiesUtil.loadFromFile(propsFile);
            dir = props.getProperty("paths.pid");
            if (dir == null) {
                dir = pidDir == null ? "/var/run" : pidDir;
            }
        }
    } catch (IOException e) {
        s_logger.debug("environment.properties could not be opened");
    }

    final File pidFile = new File(dir + File.separator + run);
    try {
        if (!pidFile.createNewFile()) {
            if (!pidFile.exists()) {
                throw new ConfigurationException("Unable to write to " + pidFile.getAbsolutePath()
                        + ".  Are you sure you're running as root?");
            }

            final String pidLine = FileUtils.readFileToString(pidFile).trim();
            if (pidLine.isEmpty()) {
                throw new ConfigurationException(
                        "Java process is being started twice.  If this is not true, remove "
                                + pidFile.getAbsolutePath());
            }
            try {
                final long pid = Long.parseLong(pidLine);
                final Script script = new Script("bash", 120000, s_logger);
                script.add("-c", "ps -p " + pid);
                final String result = script.execute();
                if (result == null) {
                    throw new ConfigurationException(
                            "Java process is being started twice.  If this is not true, remove "
                                    + pidFile.getAbsolutePath());
                }
                if (!pidFile.delete()) {
                    throw new ConfigurationException(
                            "Java process is being started twice.  If this is not true, remove "
                                    + pidFile.getAbsolutePath());
                }
                if (!pidFile.createNewFile()) {
                    throw new ConfigurationException(
                            "Java process is being started twice.  If this is not true, remove "
                                    + pidFile.getAbsolutePath());
                }
            } catch (final NumberFormatException e) {
                throw new ConfigurationException(
                        "Java process is being started twice.  If this is not true, remove "
                                + pidFile.getAbsolutePath());
            }
        }
        pidFile.deleteOnExit();

        final Script script = new Script("bash", 120000, s_logger);
        script.add("-c", "echo $PPID");
        final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
        script.execute(parser);

        final String pid = parser.getLine();

        FileUtils.writeStringToFile(pidFile, pid + "\n");
    } catch (final IOException e) {
        throw new CloudRuntimeException(
                "Unable to create the " + pidFile.getAbsolutePath() + ".  Are you running as root?", e);
    }
}

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

public static void setFilePermissionsTo700(File file) throws IOException {
    file.createNewFile();
    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) & file.setExecutable(true, true);

    if (setRead && setWrite && setExec) {
        if (LOG.isTraceEnabled())
            LOG.trace("Set permissions to 700 for file {}", file.getAbsolutePath());
    } else {/*w  w  w .  jav  a 2 s.  co m*/
        if (loggedSetFilePermissionsWarning) {
            if (LOG.isTraceEnabled())
                LOG.trace(
                        "Failed to set permissions to 700 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 700 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 700 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:Main.java

public static Bitmap decodeSampledBitmapFromUrl(String urlpath, long allowedBmpMaxMemorySize) {

    String tmpDir = System.getProperty("java.io.tmpdir", ".");
    File saveFile = new File(tmpDir, UUID.randomUUID().toString());
    if (saveFile.exists()) {
        saveFile.delete();// w w  w. j  a  v a  2s. c  om
    }
    try {
        saveFile.createNewFile();
        File ret = downloadFile(urlpath, saveFile);
        if (ret == null) {// fail.
            return null;
        }
        Bitmap bmp = decodeSampledBitmapFromPath(saveFile.getAbsolutePath(), allowedBmpMaxMemorySize);
        return bmp;
    } catch (Throwable err) {
        err.printStackTrace();

    } finally {
        if (saveFile.exists()) {
            saveFile.delete();// true.
        }
    }
    return null;
}

From source file:Main.java

/**
 * Save {@link String} to {@link File} witht the specified encoding
 *
 * @param string {@link String}//  w  w w  .  j a  va2 s . co  m
 * @param path   Path of the file
 * @param string Encoding
 * @throws IOException
 */
public static void saveStringToFile(String string, File path, String encoding) throws IOException {
    if (path.exists()) {
        path.delete();
    }

    if ((path.getParentFile().mkdirs() || path.getParentFile().exists())
            && (path.exists() || path.createNewFile())) {
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), encoding));
        writer.write(string);
        writer.close();
    }
}

From source file:com.google.codelab.networkmanager.CodelabUtil.java

/**
 * Overwrite Tasks in file with those given here.
 *///from   ww  w .ja  va2s .c om
private static void saveTaskItemsToFile(Context context, List<TaskItem> taskItems) {
    String taskStr = taskItemsToString(taskItems);
    File file = new File(context.getFilesDir(), FILE_NAME);
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }
    try {
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        IOUtils.write(taskStr, fileOutputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }
}