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:io.proleap.cobol.TestGenerator.java

public static void generateTestClass(final File cobolInputFile, final File outputDirectory,
        final String packageName) throws IOException {
    final File parentDirectory = cobolInputFile.getParentFile();
    final String inputFilename = getInputFilename(cobolInputFile);
    final File outputFile = new File(
            outputDirectory + "/" + inputFilename + OUTPUT_FILE_SUFFIX + JAVA_EXTENSION);

    final boolean createdNewFile = outputFile.createNewFile();

    if (createdNewFile) {
        LOG.info("Creating unit test {}.", outputFile);

        final PrintWriter pWriter = new PrintWriter(new FileWriter(outputFile));
        final String cobolInputFileName = cobolInputFile.getPath().replace("\\", "/");
        final CobolSourceFormat format = getCobolSourceFormat(parentDirectory);

        pWriter.write("package " + packageName + ";\n");
        pWriter.write("\n");
        pWriter.write("import java.io.File;\n");
        pWriter.write("\n");
        pWriter.write("import io.proleap.cobol.applicationcontext.CobolGrammarContextFactory;\n");
        pWriter.write("import io.proleap.cobol.preprocessor.CobolPreprocessor.CobolSourceFormatEnum;\n");
        pWriter.write("import io.proleap.cobol.runner.CobolParseTestRunner;\n");
        pWriter.write("import io.proleap.cobol.runner.impl.CobolParseTestRunnerImpl;\n");
        pWriter.write("import org.junit.Test;\n");
        pWriter.write("\n");
        pWriter.write("public class " + inputFilename + "Test {\n");
        pWriter.write("\n");
        pWriter.write("   @Test\n");
        pWriter.write("   public void test() throws Exception {\n");
        pWriter.write("      CobolGrammarContextFactory.configureDefaultApplicationContext();\n");
        pWriter.write("\n");
        pWriter.write("      final File inputFile = new File(\"" + cobolInputFileName + "\");\n");
        pWriter.write("      final CobolParseTestRunner runner = new CobolParseTestRunnerImpl();\n");
        pWriter.write("      runner.parseFile(inputFile, CobolSourceFormatEnum." + format + ");\n");
        pWriter.write("   }\n");
        pWriter.write("}");

        pWriter.flush();//w w  w  .  j  a va2s .  c  o m
        pWriter.close();
    }
}

From source file:Main.java

public static void touch(File file) throws IOException {
    if (!file.exists()) {
        File parent = file.getParentFile();
        if (parent != null)
            if (!parent.exists())
                if (!parent.mkdirs())
                    throw new IOException("Cannot create parent directories for file: " + file);
        file.createNewFile();
    }/*from  w w w  .  jav a 2  s  .  c o  m*/
}

From source file:com.normsstuff.maps4norm.Util.java

/**
 * Writes the given trace of points to the given file in CSV format,
 * separated by ";"//from w  w  w  .  j a  va  2s .com
 *
 * @param f     the file to write to
 * @param trace the trace to write
 * @throws IOException
 */
static void saveToFile(final File f, final Stack<LatLng> trace) throws IOException {
    if (!f.exists())
        f.createNewFile();
    BufferedWriter out = new BufferedWriter(new FileWriter(f));
    LatLng current;
    for (int i = 0; i < trace.size(); i++) {
        current = trace.get(i);
        out.append(String.valueOf(current.latitude)).append(";").append(String.valueOf(current.longitude))
                .append("\n");
    }
    out.close();
}

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

public static File createFileInTestDir(String fileName) throws IOException {
    final File testDirectory = getTestDir();

    final File testFile = new File(testDirectory, fileName);
    if (!testFile.createNewFile()) {
        fail("Unable to create test file: " + testFile.getAbsolutePath());
    }/*from  ww  w  . j ava2  s  . com*/
    return testFile;
}

From source file:vn.evolus.droidreader.util.ImageCache.java

public static void downloadImage(String imageUrl) throws IOException {
    HttpClient client = new DefaultHttpClient();
    HttpParams params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(params, ImageLoader.CONNECT_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, ImageLoader.READ_TIMEOUT);
    HttpGet httpGet = new HttpGet(imageUrl);
    HttpResponse response = client.execute(httpGet);
    InputStream is = response.getEntity().getContent();

    // save to cache folder
    if (Constants.DEBUG_MODE)
        Log.d(Constants.LOG_TAG, "Save image to " + getCacheFileName(imageUrl));
    File imageFile = new File(getCacheFileName(imageUrl));
    imageFile.createNewFile();
    FileOutputStream os = null;/*from   ww  w. ja va2 s. c o m*/
    try {
        os = new FileOutputStream(imageFile);
        StreamUtils.writeStream(is, os);
    } finally {
        if (os != null) {
            os.close();
        }
    }
}

From source file:com.springrts.springls.ServerNotifications.java

private static synchronized File findWriteableNotifFile(final String baseFileName) {

    File notifFile = null;/* w  ww.jav  a2 s  .  c  om*/

    int counter = 1;
    File tmpFile = null;
    do {
        tmpFile = new File(baseFileName + "_" + counter);
        counter++;
    } while (tmpFile.exists());

    try {
        if (tmpFile.createNewFile()) {
            notifFile = tmpFile;
        } else {
            throw new IOException("File already exists");
        }
    } catch (IOException ex) {
        LOG.error("Failed creating notification-file: " + tmpFile, ex);
    }

    return notifFile;
}

From source file:gov.nasa.ensemble.dictionary.nddl.NDDLUtil.java

public static String copyFile(String fileName, String outputFileName) throws IOException {

    File outputFile = new File(outputFileName);
    if (!outputFile.exists())
        outputFile.createNewFile();
    System.out.println("Copying " + fileName + " to " + outputFileName);
    OutputStream stream = new FileOutputStream(outputFile);
    InputStream input = FileLocator.openStream(Activator.getDefault().getBundle(), new Path(fileName), false);

    IOUtils.copy(input, stream);//w  w  w  . j  ava 2 s .c  o  m
    input.close();
    stream.close();
    return outputFile.getAbsolutePath();
}

From source file:edu.asu.cse564.samples.crud.io.GradebookIO.java

public static List<Gradebook> readFromGradebook(String filename) {
    //GradebookIO gbio = new GradebookIO();
    //String path = gbio.getPath(filename);
    String path = filename;/*from ww w. j av  a2s .com*/
    File file = new File(filename);

    // if file doesnt exists, then create it
    if (!file.exists()) {
        LOG.info("Creating file as it does not exits");
        try {
            file.createNewFile();
        } catch (IOException ex) {
            Logger.getLogger(GradebookIO.class.getName()).log(Level.SEVERE, null, ex);
        }
        LOG.debug("Created file = {}", file.getAbsolutePath());
        return null;
    }
    LOG.info("File path = {}", file.getAbsolutePath());
    try (BufferedReader br = new BufferedReader(new FileReader(path))) {
        StringBuilder sb = new StringBuilder();
        String sCurrentLine;

        while ((sCurrentLine = br.readLine()) != null) {
            sb.append(sCurrentLine);
        }
        if (sb.toString() != null && !sb.toString().trim().equals("")) {
            List<Gradebook> gblist = new ArrayList<Gradebook>();
            gblist = (List<Gradebook>) Converter.convertFromJsonToObject(sb.toString(),
                    new TypeReference<List<Gradebook>>() {
                    });
            return gblist;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:de.awtools.basic.file.FindFilesTest.java

@BeforeClass
public static void beforeClass() throws Exception {
    TMP_DIR = new File(SystemUtils.getUserHome(), BUILD_TMP_DIR);
    try {// ww  w. j av a2  s. com
        FileUtils.forceMkdir(TMP_DIR);
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    AWToolsFileUtils.createFilePath(TMP_DIR.getPath(), TEST_FILE);

    File file1 = new File(TMP_DIR, "findmy.txt");
    File file2 = new File(TMP_DIR, "test/winkler/findmy.txt");
    File file3 = new File(TMP_DIR, "test/winkler/arbeit/findmy.txt");

    file1.createNewFile();
    file2.createNewFile();
    file3.createNewFile();
}

From source file:net.rim.ejde.internal.legacy.Util.java

static public Workspace getDefaultLegacyWorkspace() {
    Workspace workspace = null;//w  ww  . j ava  2 s . c om

    File file = ILegacy.Workspace.getMetaFile();

    try {
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }

        workspace = new Workspace(file);

        save(workspace, true);
    } catch (Throwable t) {
        log.error(t.getMessage(), t);
    }

    return workspace;
}