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

public static void upZipFile(File zipFile, String folderPath) {
    ZipFile zf;//from   ww  w.  ja v a2 s.c  o m
    try {
        zf = new ZipFile(zipFile);
        for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
            ZipEntry entry = ((ZipEntry) entries.nextElement());
            if (entry.isDirectory()) {
                String dirstr = entry.getName();
                dirstr = new String(dirstr.getBytes("8859_1"), "GB2312");
                File f = new File(dirstr);
                f.mkdir();
                continue;
            }

            InputStream in = zf.getInputStream(entry);
            String str = folderPath + File.separator + entry.getName();
            str = new String(str.getBytes("8859_1"), "GB2312");
            File desFile = new File(str);
            if (!desFile.exists()) {
                File fileParentDir = desFile.getParentFile();
                if (!fileParentDir.exists()) {
                    fileParentDir.mkdirs();
                }
                desFile.createNewFile();
            }

            OutputStream out = new FileOutputStream(desFile);
            byte buffer[] = new byte[BUFF_SIZE];
            int realLength;
            while ((realLength = in.read(buffer)) > 0) {
                out.write(buffer, 0, realLength);
            }
            in.close();
            out.close();
        }
    } catch (ZipException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.jboss.seam.forge.shell.util.PluginUtil.java

private static File saveFile(String fileName, InputStream stream) throws IOException {
    File file = new File(fileName);
    new File(fileName.substring(0, fileName.lastIndexOf('/'))).mkdirs();

    file.createNewFile();

    OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));

    byte[] buf = new byte[127];
    int read;/*from  w ww  .  j  a  v  a 2s  .  c o m*/
    while ((read = stream.read(buf)) != -1) {
        outputStream.write(buf, 0, read);
    }

    outputStream.flush();
    outputStream.close();

    return file;
}

From source file:com.bc.fiduceo.TestUtil.java

public static void writeSystemConfig(File configDir) throws IOException {
    final String systemConfigXML = "<system-config>" + "    <geometry-library name = \"S2\" />"
            + "    <archive>" + "        <root-path>" + "            "
            + TestUtil.getTestDataDirectory().getAbsolutePath() + "        </root-path>"
            + "        <rule sensors = \"drifter-sst, ship-sst, gtmba-sst, radiometer-sst, argo-sst, xbt-sst, mbt-sst, ctd-sst, animal-sst, bottle-sst\">"
            + "            insitu/SENSOR/VERSION" + "        </rule>" + "    </archive>" + "</system-config>";

    final File systemConfigFile = new File(configDir, "system-config.xml");
    if (!systemConfigFile.createNewFile()) {
        fail("unable to create test file: " + systemConfigFile.getAbsolutePath());
    }//w  w w.j a v  a 2 s  .  co  m

    writeStringTo(systemConfigFile, systemConfigXML);
}

From source file:com.fjn.helper.common.io.file.common.FileUtil.java

/**
 * ?filename??//from ww w  . j ava  2  s  .c  o m
 * @param dir 
 * @param filename
 * @return
 */
public static File ensureFileExists(String dirPath, String filename) {
    // ??
    File dir = ensureDirExists(dirPath);
    File file = new File(dir, filename);
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return file;
}

From source file:com.fjn.helper.common.io.file.common.FileUtil.java

/**
 * ?filename??/*from   w  w  w.  j  a  v  a  2  s . co m*/
 * @param dir
 * @param filename
 * @return
 */
public static File ensureFileExists(File dir, String filename) {
    // ??
    dir = ensureDirExists(dir);
    File file = new File(dir, filename);
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return file;
}

From source file:org.shareok.data.datahandlers.DataHandlersUtil.java

@Cacheable("taskOutputFileWriter")
public static BufferedWriter getWriterForTaskOutputFile(String taskId, String taskType) throws IOException {
    String outputFilePath = ShareokdataManager.getDspaceCommandLineTaskOutputPath() + "_"
            + DataHandlersUtil.getCurrentTimeString() + "_" + taskType + "_" + taskId + ".txt";
    File outputFile = new File(outputFilePath);
    if (!outputFile.exists()) {
        outputFile.createNewFile();
    }//from   w w  w  .  j a  v a 2 s.  c om
    return new BufferedWriter(new FileWriter(outputFilePath, true));
}

From source file:com.example.SampleStreamExample.java

public static void run(String consumerKey, String consumerSecret, String token, String secret)
        throws InterruptedException {
    // Create an appropriately sized blocking queue
    BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000);

    // Define our endpoint: By default, delimited=length is set (we need this for our processor)
    // and stall warnings are on.
    StatusesSampleEndpoint endpoint = new StatusesSampleEndpoint();
    endpoint.stallWarnings(false);// ww  w.j  a  v a  2  s. co m

    File file = new File("/usr/local/Output11.txt");

    if (!file.exists()) {
        try {
            file.createNewFile();
            FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("[");
            bw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    Authentication auth = new OAuth1(consumerKey, consumerSecret, token, secret);
    //Authentication auth = new com.twitter.hbc.httpclient.auth.BasicAuth(username, password);

    // Create a new BasicClient. By default gzip is enabled.
    BasicClient client = new ClientBuilder().name("sampleExampleClient").hosts(Constants.STREAM_HOST)
            .endpoint(endpoint).authentication(auth).processor(new StringDelimitedProcessor(queue)).build();

    // Establish a connection
    client.connect();

    // Do whatever needs to be done with messages
    for (int msgRead = 0; msgRead < 1000; msgRead++) {
        if (client.isDone()) {
            System.out.println("Client connection closed unexpectedly: " + client.getExitEvent().getMessage());
            break;
        }

        String msg = queue.poll(5, TimeUnit.SECONDS);
        //  String Time="time",Text="Text";
        //Lang id;
        if (msg == null) {
            System.out.println("Did not receive a message in 5 seconds");
        } else {

            System.out.println(msg);
            //System.out.println("**************hahahahahahahah********************");

            try {
                FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
                BufferedWriter bw = new BufferedWriter(fw);

                if (msgRead == 999)
                    bw.write(msg);
                else
                    bw.write(msg + ",");

                bw.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            /*     JSONParser jsonParser = new JSONParser();
                   //JsonElement jsonElement = null;
                           
                   String key="";
                try {
                   //jsonElement= (JsonElement) jsonParser.parse(msg); 
                 JSONObject jsonObject = (JSONObject) jsonParser.parse(msg);
                 //JsonObject jsonObjec = jsonElement.getAsJsonObject();
                 //for(Entry<String, JsonElement> entry : jsonObjec.entrySet())
              //   {  key = entry.getKey();
                 //   if(key=="delete")
                    //      System.out.println("this comment is deleted");
              //   }   
                   //JsonElement value = entry.getValue();
                         
                 //***** printing date
              //   Time = (String) jsonObject.get("created_at");
                    System.out.println("Date of creation====: " + jsonObject.get("created_at"));
                    //******printing id
                  //   id = (Lang) jsonObject.get("id");
                 //   System.out.println("id=========: " + jsonObject.get("id"));
                    //*******text
                     //Text = (String) jsonObject.get("text");
                   //System.out.println("Text==========: " + jsonObject.get("text"));
                            
                    //************inside user************
                    JSONObject structure = (JSONObject) jsonObject.get("user");
                    System.out.println("Into user structure ,  id====: " + structure.get("id"));
                    System.out.println("Into user structure ,  name====: " + structure.get("name"));
                    System.out.println("Into user structure ,  screen_name====: " + structure.get("screen_name"));
                    System.out.println("Into user structure ,  location====: " + structure.get("location"));
                    System.out.println("Into user structure ,  description====: " + structure.get("description"));
                    System.out.println("Into user structure ,  followers====: " + structure.get("followers_count"));
                    System.out.println("Into user structure ,  friends====: " + structure.get("friends_count"));
                    System.out.println("Into user structure ,  listed====: " + structure.get("listed_count"));
                    System.out.println("Into user structure ,  favorite====: " + structure.get("favorites_count"));
                    System.out.println("Into user structure ,  status_count====: " + structure.get("status_count"));
                    System.out.println("Into user structure ,  created at====: " + structure.get("created at"));
                            
                            
                            
                         
              } catch (ParseException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
              }
                    
                  */
        }
    }
    FileWriter fw;
    try {
        fw = new FileWriter(file.getAbsoluteFile(), true);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write("]");
        bw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    client.stop();

    // Print some stats
    System.out.printf("The client read %d messages!\n", client.getStatsTracker().getNumMessages());

}

From source file:be.i8c.sag.util.FileUtils.java

/**
 * Creates the file if it doesn't exist yet
 *
 * @param file The file to create// w  ww .  java2  s .c o  m
 * @return The same file that was passed
 * @throws IOException When failed to write to a file
 */
public static File createFile(File file) throws IOException {
    if (!file.exists()) {
        if (file.getParentFile() != null)
            file.getParentFile().mkdirs();
        file.createNewFile();
    }

    return file;
}

From source file:com.thinkit.operationsys.util.FileUtil.java

/**
 * @param topath   /*from  ww w  . ja va 2 s  .co  m*/
 * @param frompath 
 * @throws IOException
 */
public static void startCopy(String src, String dest) throws IOException {
    System.out.println("copy");
    //??
    File srcfile = new File(src);
    File destfile = new File(dest);

    if (srcfile.exists() && destfile.exists()) {
        FileUtils.copyFile(srcfile, destfile);
    } else {
        srcfile.getParentFile().mkdirs();
        try {
            srcfile.createNewFile();
        } catch (IOException e) {
            logger.info("create  file error");
            e.printStackTrace();
        }
        destfile.getParentFile().mkdirs();
        try {
            destfile.createNewFile();
        } catch (IOException e) {
            logger.info("create  file error");
            e.printStackTrace();
        }
    }

}

From source file:jp.furplag.util.commons.FileUtils.java

private static boolean createNewFile(String filename, boolean printStackTrace) {
    try {//w w w  .j av a  2  s  . c o m
        if (StringUtils.isSimilarToBlank(filename))
            throw new IOException("path must not be empty.");
        String path = normalize(filename);
        File file = new File(path);
        if (file.exists() && file.isDirectory())
            throw new IOException(normalize(file.getAbsolutePath()) + " is directory.");
        path = normalize(file.getAbsolutePath());
        forceMkdir(StringUtils.truncateLast(path, "/.*"));
        if (!file.exists())
            return file.createNewFile();

    } catch (Exception e) {
        if (printStackTrace)
            e.printStackTrace();
    }

    return false;
}