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:org.apache.hadoop.gateway.SecureClusterTest.java

private static File setupJaasConf(File baseDir, String keyTabFile, String principal) throws IOException {
    File file = new File(baseDir, "jaas.conf");
    if (!file.exists()) {
        file.createNewFile();
    } else {/*from w w w  .  java  2  s .  c  om*/
        file.delete();
        file.createNewFile();
    }
    FileWriter writer = new FileWriter(file);
    String content = String.format("com.sun.security.jgss.initiate {\n"
            + "com.sun.security.auth.module.Krb5LoginModule required\n" + "renewTGT=true\n"
            + "doNotPrompt=true\n" + "useKeyTab=true\n" + "keyTab=\"%s\"\n" + "principal=\"%s\"\n"
            + "isInitiator=true\n" + "storeKey=true\n" + "useTicketCache=true\n" + "client=true;\n" + "};\n",
            keyTabFile, principal);
    writer.write(content);
    writer.close();
    return file;
}

From source file:com.ibm.watson.developer_cloud.professor_languo.ingestion.indexing.StackExchangeThreadSerializer.java

/**
 * Serialize a StackExchangeThread into a binary file
 * //  www. ja  v a  2s  .c o m
 * @param threadToSerialize - The StackExchangeThread to be serialized
 * @return the path(relative to the resource folder) of the serialized binary file
 * @throws IngestionException
 */
public static String serializeThreadToBinFile(StackExchangeThread threadToSerialize, String dirPath)
        throws IngestionException {
    String binFileName = threadToSerialize.getId() + StackExchangeConstants.BIN_FILE_SUFFIX;
    try {
        String binFilePath = dirPath + binFileName;
        File serFile = new File(binFilePath);
        if (serFile.getParentFile() != null)
            serFile.getParentFile().mkdirs();
        if (!serFile.exists())
            serFile.createNewFile();
        OutputStream binOut = new FileOutputStream(serFile);
        ObjectOutputStream out = new ObjectOutputStream(binOut);
        out.writeObject(threadToSerialize);
        out.close();
        binOut.close();
    } catch (IOException e) {
        throw new IngestionException(e);
    }
    return binFileName;
}

From source file:com.stratio.crossdata.sh.utils.ConsoleUtils.java

/**
 * This method save history extracted from the Crossdata console to be persisted in the disk.
 *
 * @param console Crossdata console created from a JLine console
 * @param file    represents the file to be created of updated with the statements from the current
 *                session//  w ww.  ja  v a2s . co  m
 * @param sdf     Simple Date Format to create dates for the history file
 * @throws IOException file couldn't be created or read
 */
public static void saveHistory(ConsoleReader console, File file, SimpleDateFormat sdf) throws IOException {
    boolean created = file.createNewFile();
    OutputStreamWriter isr;
    if (created) {
        isr = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
    } else {
        isr = new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8");
    }
    try (BufferedWriter bufferWriter = new BufferedWriter(isr)) {
        History history = console.getHistory();
        ListIterator<History.Entry> histIter = history.entries();
        while (histIter.hasNext()) {
            History.Entry entry = histIter.next();
            bufferWriter.write(sdf.format(new Date()));
            bufferWriter.write("|");
            bufferWriter.write(entry.value().toString());
            bufferWriter.newLine();
        }
        bufferWriter.flush();
    }
}

From source file:de.matzefratze123.staffinformer.util.IOUtil.java

public static void copy(InputStream stream, File output) throws IOException {
    Validate.notNull(stream, "InputStream cannot be null");
    Validate.notNull(output, "Output file cannot be null");

    final int BUFFER_SIZE = 1024;

    OutputStream outStream = null;

    try {/*from  w w w  . j a v a2s. c  o m*/
        if (!output.exists()) {
            output.createNewFile();
        }

        outStream = new FileOutputStream(output);

        byte[] buffer = new byte[BUFFER_SIZE];
        int read;

        while ((read = stream.read(buffer)) > 0) {
            outStream.write(buffer, 0, read);
        }

        outStream.flush();
    } finally {
        try {
            if (stream != null) {
                stream.close();
            }
            if (outStream != null) {
                outStream.close();
            }
        } catch (Exception e) {
        }
    }
}

From source file:prince.app.sphotos.Gallery.UriTexture.java

public static void writeToCache(long crc64, Bitmap bitmap, int maxResolution) {
    String file = createFilePathFromCrc64(crc64, maxResolution);
    if (bitmap != null && file != null && crc64 != 0) {
        try {// ww  w.j av a  2s .c  o m
            File fileC = new File(file);
            fileC.createNewFile();
            final FileOutputStream fos = new FileOutputStream(fileC);
            final BufferedOutputStream bos = new BufferedOutputStream(fos, 16384);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
            bos.flush();
            bos.close();
            fos.close();
            Log.i(TAG, "written to cache at: " + fileC.getAbsolutePath());
        } catch (Exception e) {

        }
    }
}

From source file:com.amazonaws.utilities.Util.java

/**
 * Copies the data from the passed in Uri, to a new file for use with the
 * Transfer Service/*from  w  w w  .  j av  a2 s .  c  o  m*/
 * 
 * @param context
 * @param uri
 * @return
 * @throws IOException
 */
public static File copyContentUriToFile(Context context, Uri uri) throws IOException {
    InputStream is = context.getContentResolver().openInputStream(uri);
    File copiedData = new File(context.getDir("SampleImagesDir", Context.MODE_PRIVATE),
            UUID.randomUUID().toString());
    copiedData.createNewFile();

    FileOutputStream fos = new FileOutputStream(copiedData);
    byte[] buf = new byte[2046];
    int read = -1;
    while ((read = is.read(buf)) != -1) {
        fos.write(buf, 0, read);
    }

    fos.flush();
    fos.close();

    return copiedData;
}

From source file:index.IncrementIndex.java

/**
* 
* @param path/*from  www  .j a v  a  2 s . c o  m*/
* @param storeIdPath
* @param rs
* @return 
*/
public static boolean indexBuilding(String path, String storeIdPath, ResultSet rs, String classPath,
        String keyName) throws SQLException {
    try {
        Analyzer luceneAnalyzer = new StandardAnalyzer();
        // ??ID??  
        boolean isEmpty = true;
        try {
            File file = new File(storeIdPath);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileReader fr = new FileReader(storeIdPath);
            BufferedReader br = new BufferedReader(fr);
            if (br.readLine() != null) {
                isEmpty = false;
            }
            br.close();
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //isEmpty=false?  
        IndexWriter writer = new IndexWriter(path, luceneAnalyzer, isEmpty);
        String storeId = "";
        boolean indexFlag = false;
        // ?
        Class c2 = Class.forName(classPath);
        // 
        java.lang.reflect.Field[] fields = c2.getDeclaredFields();
        while (rs.next()) {
            // list?    
            Map map = new HashMap();
            // ????
            for (java.lang.reflect.Field field : fields) {
                //  
                if (keyName.equals(field.getName())) {
                    storeId = rs.getString(field.getName().toUpperCase());
                }
                // ???
                if (whetherExist(field.getName().toUpperCase(), rs)) {
                    map.put(field.getName(), rs.getString(field.getName().toUpperCase()));
                }
            }
            writer.addDocument(Document(map));
            indexFlag = true;
        }
        writer.optimize();
        writer.close();
        if (indexFlag) {
            // ?ID?  
            writeStoreId(storeIdPath, storeId);
        }
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("" + e.getClass() + "\n   ?:   " + e.getMessage());
        return false;
    } finally {
        if (null != rs) {
            rs.close();
        }
    }

}

From source file:com.ibuildapp.romanblack.CataloguePlugin.imageloader.Utils.java

public static String downloadFile(Context context, String url, String md5) {
    final int BYTE_ARRAY_SIZE = 8024;
    final int CONNECTION_TIMEOUT = 30000;
    final int READ_TIMEOUT = 30000;

    try {/*  w  w  w .j av  a 2 s.  c  om*/
        for (int i = 0; i < 3; i++) {
            URL fileUrl = new URL(URLDecoder.decode(url));
            HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection();
            connection.setConnectTimeout(CONNECTION_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.connect();

            int status = connection.getResponseCode();

            if (status >= HttpStatus.SC_BAD_REQUEST) {
                connection.disconnect();

                continue;
            }

            BufferedInputStream bufferedInputStream = new BufferedInputStream(connection.getInputStream());
            File file = new File(StaticData.getCachePath(context) + md5);

            if (!file.exists()) {
                new File(StaticData.getCachePath(context)).mkdirs();
                file.createNewFile();
            }

            FileOutputStream fileOutputStream = new FileOutputStream(file, false);
            int byteCount;
            byte[] buffer = new byte[BYTE_ARRAY_SIZE];

            while ((byteCount = bufferedInputStream.read(buffer, 0, BYTE_ARRAY_SIZE)) != -1)
                fileOutputStream.write(buffer, 0, byteCount);

            bufferedInputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();

            return file.getAbsolutePath();
        }
    } catch (Exception e) {
        e.printStackTrace();

        return null;
    }

    return null;
}

From source file:com.sugarcrm.candybean.datasource.CsvDataAdapterSystemTest.java

private static void createFile(String dir, String filename, String content) {
    try {//  www .  j av a 2  s .c om
        File file = new File(dir + File.separator + filename);

        // Create file if not exist
        if (!file.exists()) {
            file.createNewFile();
            System.out.println("createFile(): created " + file.getAbsolutePath());
        } else {
            System.out.println("createFile(): " + file.getAbsolutePath() + " already exists");
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();

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

From source file:com.mewin.util.Utils.java

public static void createDefaultConfig(Plugin plugin) {
    FileOutputStream out = null;/*from   w  w w  .jav a  2  s .c o  m*/
    InputStream in = null;
    try {
        File configFile = new File(plugin.getDataFolder(), "/config.yml");

        if (!plugin.getDataFolder().exists()) {
            plugin.getDataFolder().mkdirs();
        }

        if (!configFile.exists()) {
            configFile.createNewFile();
        }

        out = new FileOutputStream(configFile);
        in = plugin.getResource("config.yml");

        int next;
        while ((next = in.read()) >= 0) {
            out.write(next);
        }
    } catch (IOException ex) {
        plugin.getLogger().log(Level.SEVERE, "Could not create default configuration file: ", ex);
    } finally {
        try {
            if (in != null) {
                in.close();
            }

            if (out != null) {
                out.close();
            }
        } catch (IOException ex) {
        }
    }
}