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:de.teamgrit.grit.report.PdfConcatenator.java

/**
 * Concatinates pdfs generated {@link TexGenerator}.
 *
 * @param folderWithPdfs/*from   w ww  . j  a  v a  2s .  c  o  m*/
 *            the folder with pdfs
 * @param outPath
 *            the out path
 * @param exerciseName
 *            the context
 * @param studentsWithoutSubmissions
 *            list of students who did not submit any solution
 * @return the path to the created PDF
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
protected static Path concatPDFS(Path folderWithPdfs, Path outPath, String exerciseName,
        List<Student> studentsWithoutSubmissions) throws IOException {

    if ((folderWithPdfs == null) || !Files.isDirectory(folderWithPdfs)) {
        throw new IOException("The Path doesn't point to a Folder");
    }

    File file = new File(outPath.toFile(), "report.tex");

    if (Files.exists(file.toPath(), LinkOption.NOFOLLOW_LINKS)) {
        Files.delete(file.toPath());
    }
    file.createNewFile();

    writePreamble(file, exerciseName);
    writeMissingStudents(file, studentsWithoutSubmissions);
    writeFiles(file, folderWithPdfs);
    writeClosing(file);

    PdfCreator.createPdfFromPath(file.toPath(), outPath);

    return file.toPath();

}

From source file:eu.trentorise.opendata.josman.test.GitTest.java

private static File createSampleGitRepo() throws IOException, GitAPIException {
    Repository repository = CookbookHelper.createNewRepository();

    System.out.println("Temporary repository at " + repository.getDirectory());

    // create the file
    File myfile = new File(repository.getDirectory().getParent(), "testfile");
    myfile.createNewFile();

    // run the add-call
    new Git(repository).add().addFilepattern("testfile").call();

    // and then commit the changes
    new Git(repository).commit().setMessage("Added testfile").call();

    LOG.info("Added file " + myfile + " to repository at " + repository.getDirectory());

    File dir = repository.getDirectory();

    repository.close();// w  w w. j  av  a2s . c om

    return dir;

}

From source file:com.cooliris.media.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 {//from  w  w w. j av a 2 s. c om
            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();
        } catch (Exception e) {

        }
    }
}

From source file:Main.java

public static boolean saveObjectToFile(String filePath, Object object) {
    if (!TextUtils.isEmpty(filePath)) {
        File cacheFile = null;

        try {//  w  w w  .  j a va 2  s  .  c om
            cacheFile = new File(filePath);
            if (cacheFile.exists()) {
                cacheFile.delete();
            }

            if (!cacheFile.getParentFile().exists()) {
                cacheFile.getParentFile().mkdirs();
            }

            cacheFile.createNewFile();
        } catch (Throwable var6) {
            var6.printStackTrace();
            cacheFile = null;
        }

        if (cacheFile != null) {
            try {
                FileOutputStream t = new FileOutputStream(cacheFile);
                GZIPOutputStream gzos = new GZIPOutputStream(t);
                ObjectOutputStream oos = new ObjectOutputStream(gzos);
                oos.writeObject(object);
                oos.flush();
                oos.close();
                return true;
            } catch (Throwable var7) {
                var7.printStackTrace();
            }
        }
    }

    return false;
}

From source file:net.mindengine.blogix.BlogixMain.java

private static void createCategory(String title) throws Exception {
    if (title.isEmpty()) {
        error("Title should not be empty");
    }//from   ww w.  j av  a  2  s. co m
    StringBuffer buff = new StringBuffer();
    buff.append("----\n");
    buff.append("name\n");
    buff.append("   ");
    buff.append(title);
    buff.append("\n");

    String fileName = title.toLowerCase().replaceAll("\\s+", " ").replaceAll("\\s", "-");
    String fullPath = "db" + File.separator + "categories" + File.separator + fileName + _BLOGIX_SUFFIX;
    File file = new File(fullPath);
    file.createNewFile();
    FileUtils.writeStringToFile(file, buff.toString());
    info("created " + fullPath);
}

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

public static String getLoggingForUserFilePath(String taskId, String taskType) throws IOException {
    String outputFileContainerPath = getTaskFileFolderPath(taskId, taskType);
    File outputFile = new File(outputFileContainerPath + File.separator + "userInputInfo.txt");
    if (!outputFile.exists()) {
        outputFile.createNewFile();
    }// w  w w .j  a  v a2s  .  c  o m
    return outputFile.getAbsolutePath();
}

From source file:de.uniluebeck.itm.spyglass.SpyglassEnvironment.java

/**
 * Create a default property file//from w  ww.java  2  s.c o m
 * @param f the file to write to
 */
private static void createDefaultConfig(final File f) throws IOException {
    if (!f.createNewFile()) {
        throw new IOException("Could not create property file!");
    }
    final Properties props = new Properties();
    final InputStream input = new FileInputStream(f);

    props.load(input);
    props.setProperty(PROPERTY_CONFIG_FILE_WORKING_DIR, "config/");
    props.setProperty(PROPERTY_CONFIG_FILE_IMAGE_DIR, "image/");
    props.setProperty(PROPERTY_CONFIG_RECORD_DIR, "record/");
    props.setProperty(PROPERTY_CONFIG_STANDALONE_SIZE_X, "800");
    props.setProperty(PROPERTY_CONFIG_STANDALONE_SIZE_Y, "600");
    props.setProperty(PROPERTY_CONFIG_DRAWINGAREA_SIZE, "83");
    props.setProperty(PROPERTY_CONFIG_AFFINE_TRANSFORM_MATRIX, "1.0,0.0,0.0,1.0,0.0,1.0");
    props.setProperty(PROPERTY_CONFIG_DRAWINGAREA_POSITION, "0,0,1000,500");

    storeProps(props);
}

From source file:net.jmhertlein.alphonseirc.MSTDeskEngRunner.java

private static void loadConfig() {
    boolean read = false;
    File f = CONFIG_FILE;
    if (!f.exists()) {
        read = true;//from w  ww  .j av  a 2 s.c  o m
        try {
            f.getParentFile().mkdirs();
            f.createNewFile();
            java.nio.file.Files.setPosixFilePermissions(Paths.get(f.toURI()),
                    PosixFilePermissions.fromString("rw-------"));
        } catch (IOException ex) {
            Logger.getLogger(MSTDeskEngRunner.class.getName()).log(Level.SEVERE, null, ex);
            System.err.println("Error writing empty config.yml!");
        }
    }

    Map<String, Object> config;

    if (read) {
        Console console = System.console();
        console.printf("Nick: \n->");
        nick = console.readLine();
        console.printf("\nPassword: \n-|");
        pass = new String(console.readPassword());
        console.printf("\nServer: \n->");
        server = console.readLine();
        console.printf("\nChannels: (ex: #java,#linux,#gnome)\n->");
        channels = Arrays.asList(console.readLine().split(","));
        System.out.println("Fetching max XKCD...");
        maxXKCD = fetchMaxXKCD();
        System.out.println("Fetched.");
        cachedUTC = System.currentTimeMillis();

        dadLeaveTimes = new HashMap<>();
        noVoiceNicks = new HashSet<>();

        writeConfig();
        System.out.println("Wrote config to file: " + CONFIG_FILE.getAbsolutePath());

    } else {
        try (FileInputStream fis = new FileInputStream(f)) {
            Yaml y = new Yaml();
            config = y.loadAs(fis, Map.class);
        } catch (IOException ex) {
            Logger.getLogger(MSTDeskEngRunner.class.getName()).log(Level.SEVERE, null, ex);
            System.err.println("Error parsing config!");
            return;
        }

        nick = (String) config.get("nick");
        pass = (String) config.get("password");
        server = (String) config.get("server");
        channels = (List<String>) config.get("channels");
        maxXKCD = (Integer) config.get("cachedMaxXKCD");
        cachedUTC = (Long) config.get("cachedUTC");
        noVoiceNicks = (Set<String>) config.get("noVoiceNicks");
        masters = (Set<String>) config.get("masters");
        if (masters == null) {
            masters = new HashSet<>();
            masters.add("Everdras");
        }

        if (noVoiceNicks == null)
            noVoiceNicks = new HashSet<>();

        noVoiceNicks.stream().forEach((s) -> System.out.println("Loaded novoice nick: " + s));
        masters.stream().forEach((s) -> System.out.println("Loaded master nick: " + s));

        if (checkXKCDUpdate())
            writeConfig();
        else
            System.out.println("Loaded cached XKCD.");

        Map<String, Object> serialDadLeaveTimes = (Map<String, Object>) config.get("dadLeaveTimes");
        dadLeaveTimes = new HashMap<>();
        if (serialDadLeaveTimes != null)
            serialDadLeaveTimes.keySet().stream().forEach((time) -> {
                dadLeaveTimes.put(LocalDate.parse(time),
                        LocalTime.parse((String) serialDadLeaveTimes.get(time)));
            });

    }
}

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

/**
 * Get previous history of the Crossdata console from a file.
 *
 * @param console Crossdata console created from a JLine console
 * @param sdf     Simple Date Format to read dates from history file
 * @return File inserted in the JLine console with the previous history
 * @throws IOException/*www  .  j av  a2s .  co  m*/
 */
public static File retrieveHistory(ConsoleReader console, SimpleDateFormat sdf) throws IOException {
    Date today = new Date();
    String workingDir = System.getProperty("user.home");
    File dir = new File(workingDir, ".com.stratio.crossdata");
    if (!dir.exists() && !dir.mkdir()) {
        LOG.error("Cannot create history directory: " + dir.getAbsolutePath());
    }
    File file = new File(dir.getPath() + "/history.txt");
    if (!file.exists() && !file.createNewFile()) {
        LOG.error("Cannot create history file: " + file.getAbsolutePath());
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Retrieving history from " + file.getAbsolutePath());
    }
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
    History oldHistory = new MemoryHistory();
    DateTime todayDate = new DateTime(today);
    String line;
    String[] lineArray;
    Date lineDate;
    String lineStatement;
    try {
        while ((line = br.readLine()) != null) {
            lineArray = line.split("\\|");
            lineDate = sdf.parse(lineArray[0]);
            if (Days.daysBetween(new DateTime(lineDate), todayDate).getDays() < DAYS_HISTORY_ENTRY_VALID) {
                lineStatement = lineArray[1];
                oldHistory.add(lineStatement);
            }
        }
    } catch (ParseException ex) {
        LOG.error("Cannot parse date", ex);
    } catch (Exception ex) {
        LOG.error("Cannot read all the history", ex);
    } finally {
        br.close();
    }
    console.setHistory(oldHistory);
    LOG.info("History retrieved");
    return file;
}

From source file:Main.java

/** Write the text provided to a File.
 * // ww  w . j a va  2s  .c o m
 * @param file the file to write to.
 * @param text the text to write.
 * @throws IOException
 */
public static void write(File file, String text) throws IOException {
    FileOutputStream out = null;
    try {
        file.getParentFile().mkdirs();
        file.delete();
        file.createNewFile();
        out = new FileOutputStream(file);
        OutputStreamWriter writer = new OutputStreamWriter(out);
        writer.write(text);
        writer.flush();
    } finally {
        try {
            out.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}