Example usage for java.nio.file StandardOpenOption CREATE

List of usage examples for java.nio.file StandardOpenOption CREATE

Introduction

In this page you can find the example usage for java.nio.file StandardOpenOption CREATE.

Prototype

StandardOpenOption CREATE

To view the source code for java.nio.file StandardOpenOption CREATE.

Click Source Link

Document

Create a new file if it does not exist.

Usage

From source file:org.wso2.msf4j.perftest.echo.springboot.EchoService.java

@RequestMapping("/EchoService/fileecho")
@ResponseBody//from  w w  w .j  av a 2 s. co  m
public String fileWrite(@RequestBody String body) throws InterruptedException, IOException {
    String returnStr = "";
    java.nio.file.Path tempfile = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
    Files.write(tempfile, body.getBytes(Charset.defaultCharset()), StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING);
    returnStr = new String(Files.readAllBytes(tempfile), Charset.defaultCharset());
    Files.delete(tempfile);
    return returnStr;
}

From source file:org.schedulesdirect.api.utils.HttpUtils.java

static public void captureToDisk(String msg) {
    Config conf = Config.get();//from  w  ww. j a  v a 2 s.c om
    if (conf.captureHttpComm()) {
        if (!auditSetup)
            setupAudit();

        try {
            if (AUDIT_LOG != null)
                synchronized (HttpUtils.class) {
                    Files.write(AUDIT_LOG, msg.getBytes("UTF-8"), StandardOpenOption.APPEND,
                            StandardOpenOption.WRITE, StandardOpenOption.CREATE);
                }
        } catch (IOException e) {
            LOG.error("Unable to write capture file, logging at trace level instead!", e);
            LOG.trace(msg);
        }
    }
}

From source file:org.eclipse.winery.repository.backend.filebased.AutoSaveListener.java

@Override
public void configurationChanged(ConfigurationEvent event) {
    if (!event.isBeforeUpdate()) {
        try {/*  w w  w .  j av  a  2  s  .  co m*/
            if (!Files.exists(this.path.getParent())) {
                Files.createDirectories(this.path.getParent());
            }
        } catch (IOException ce) {
            AutoSaveListener.logger.error("Could not update properties file", ce);
            return;
        }
        try (OutputStream out = Files.newOutputStream(this.path, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING)) {
            OutputStreamWriter writer = new OutputStreamWriter(out);
            this.configuration.save(writer);
        } catch (ConfigurationException | IOException ce) {
            AutoSaveListener.logger.error("Could not update properties file", ce);
        }
    }
}

From source file:com.surevine.gateway.scm.git.jgit.TestUtility.java

public static LocalRepoBean createTestRepoMultipleBranches() throws Exception {
    final String projectKey = "test_" + UUID.randomUUID().toString();
    final String repoSlug = "testRepo";
    final String remoteURL = "ssh://fake_url";
    final Path repoPath = Paths.get(PropertyUtil.getGitDir(), "local_scm", projectKey, repoSlug);
    Files.createDirectories(repoPath);
    final Repository repo = new FileRepository(repoPath.resolve(".git").toFile());
    repo.create();/* w  w  w.  java  2  s  .  co m*/
    final StoredConfig config = repo.getConfig();
    config.setString("remote", "origin", "url", remoteURL);
    config.save();

    final LocalRepoBean repoBean = new LocalRepoBean();
    repoBean.setProjectKey(projectKey);
    repoBean.setSlug(repoSlug);
    repoBean.setLocalBare(false);

    final Git git = new Git(repo);

    // add some files to some branches
    for (int i = 0; i < 3; i++) {
        final String filename = "newfile" + i + ".txt";
        Files.write(repoPath.resolve(filename), Arrays.asList("Hello World"), StandardCharsets.UTF_8,
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        git.add().addFilepattern(filename).call();
        git.commit().setMessage("Added " + filename).call();
    }

    git.checkout().setName("branch1").setCreateBranch(true).call();
    for (int i = 0; i < 3; i++) {
        final String filename = "branch1" + i + ".txt";
        Files.write(repoPath.resolve(filename), Arrays.asList("Hello World"), StandardCharsets.UTF_8,
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        git.add().addFilepattern(filename).call();
        git.commit().setMessage("Added " + filename).call();
    }

    git.checkout().setName("master").call();
    git.checkout().setName("branch2").setCreateBranch(true).call();
    for (int i = 0; i < 3; i++) {
        final String filename = "branch2" + i + ".txt";
        Files.write(repoPath.resolve(filename), Arrays.asList("Hello World"), StandardCharsets.UTF_8,
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        git.add().addFilepattern(filename).call();
        git.commit().setMessage("Added " + filename).call();
    }

    repo.close();
    return repoBean;
}

From source file:com.scaniatv.LangFileUpdater.java

/**
 * Method that updates a custom lang file.
 * /*from w w  w  .java 2  s . c  o m*/
 * @param stringArray 
 * @param langFile 
 */
public static void updateCustomLang(String stringArray, String langFile) {
    final StringBuilder sb = new StringBuilder();
    final JSONArray array = new JSONArray(stringArray);

    for (int i = 0; i < array.length(); i++) {
        JSONObject obj = array.getJSONObject(i);

        sb.append("$.lang.register('" + obj.getString("id") + "', '"
                + sanitizeResponse(obj.getString("response")) + "');\n");
    }

    try {
        langFile = CUSTOM_LANG_ROOT + langFile.replaceAll("\\\\", "/");

        File file = new File(langFile);
        boolean exists = true;

        // Make sure the folder exists.
        if (!file.getParentFile().isDirectory()) {
            file.getParentFile().mkdirs();
        }

        // This is used if we need to load the script or not.
        if (!file.exists()) {
            exists = false;
        }

        // Write the data.
        Files.write(Paths.get(langFile), sb.toString().getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);

        // If the script doesn't exist, load it.
        if (!exists) {
            ScriptManager.loadScript(file);
        }
    } catch (IOException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    }
}

From source file:org.diorite.impl.plugin.PluginManagerImpl.java

public static void saveCache() {
    try {//from w w  w. j  a  va2 s  .  c  o  m
        Files.write(new File("pluginsCache.txt").toPath(),
                mainClassCache.entrySet().stream().map(e -> e.getValue() + CACHE_PATTERN_SEP + e.getKey())
                        .collect(Collectors.toList()),
                StandardCharsets.UTF_8, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
    } catch (final Exception e) {
        if (CoreMain.isEnabledDebug()) {
            e.printStackTrace();
        }
    }
}

From source file:org.wurtele.ifttt.watchers.WorkTimesWatcher.java

private void processFile(Path input) {
    logger.info("Updating " + output);

    try (Workbook wb = new XSSFWorkbook();
            OutputStream out = Files.newOutputStream(output, StandardOpenOption.CREATE,
                    StandardOpenOption.TRUNCATE_EXISTING)) {
        Sheet sheet = wb.createSheet("Time Sheet");
        List<WorkDay> days = new ArrayList<>();
        DateFormat df = new SimpleDateFormat("MMMM dd, yyyy 'at' hh:mma");
        for (String line : Files.readAllLines(input)) {
            String[] data = line.split(";");
            LocationType type = LocationType.valueOf(data[0].toUpperCase());
            Date time = df.parse(data[1]);
            Date day = DateUtils.truncate(time, Calendar.DATE);
            WorkDay wd = new WorkDay(day);
            if (days.contains(wd))
                wd = days.get(days.indexOf(wd));
            else//from   w w  w  . j av  a 2 s  . c  o m
                days.add(wd);
            wd.getTimes().add(new WorkTime(time, type));
        }

        CreationHelper helper = wb.getCreationHelper();
        Font bold = wb.createFont();
        bold.setBoldweight(Font.BOLDWEIGHT_BOLD);

        CellStyle dateStyle = wb.createCellStyle();
        dateStyle.setDataFormat(helper.createDataFormat().getFormat("MMMM d, yyyy"));
        CellStyle timeStyle = wb.createCellStyle();
        timeStyle.setDataFormat(helper.createDataFormat().getFormat("h:mm AM/PM"));
        CellStyle headerStyle = wb.createCellStyle();
        headerStyle.setAlignment(CellStyle.ALIGN_CENTER);
        headerStyle.setFont(bold);
        CellStyle totalStyle = wb.createCellStyle();
        totalStyle.setAlignment(CellStyle.ALIGN_RIGHT);

        Row header = sheet.createRow(0);
        header.createCell(0).setCellValue("DATE");
        header.getCell(0).setCellStyle(headerStyle);

        Collections.sort(days);
        for (int r = 0; r < days.size(); r++) {
            WorkDay day = days.get(r);
            Row row = sheet.createRow(r + 1);
            row.createCell(0).setCellValue(day.getDate());
            row.getCell(0).setCellStyle(dateStyle);
            Collections.sort(day.getTimes());
            for (int c = 0; c < day.getTimes().size(); c++) {
                WorkTime time = day.getTimes().get(c);
                if (sheet.getRow(0).getCell(c + 1) != null
                        && !sheet.getRow(0).getCell(c + 1).getStringCellValue().equals(time.getType().name())) {
                    throw new Exception("Invalid data");
                } else if (sheet.getRow(0).getCell(c + 1) == null) {
                    sheet.getRow(0).createCell(c + 1).setCellValue(time.getType().name());
                    sheet.getRow(0).getCell(c + 1).setCellStyle(headerStyle);
                }
                row.createCell(c + 1).setCellValue(time.getTime());
                row.getCell(c + 1).setCellStyle(timeStyle);
            }
        }

        int totalCol = header.getLastCellNum();
        header.createCell(totalCol).setCellValue("TOTAL");
        header.getCell(totalCol).setCellStyle(headerStyle);

        for (int r = 0; r < days.size(); r++) {
            sheet.getRow(r + 1).createCell(totalCol).setCellValue(days.get(r).getTotal());
            sheet.getRow(r + 1).getCell(totalCol).setCellStyle(totalStyle);
        }

        for (int c = 0; c <= totalCol; c++) {
            sheet.autoSizeColumn(c);
        }

        wb.write(out);
    } catch (Exception e) {
        logger.error("Failed to update " + output, e);
    }
}

From source file:net.sf.jclal.listener.RealScenarioListener.java

/**
 * {@inheritDoc}/*from   w w w. j  ava2 s .c  o m*/
 */
@Override
public void algorithmStarted(AlgorithmEvent event) {

    super.algorithmStarted(event);

    in = new BufferedReader(new InputStreamReader(System.in));

    if (getInformativeInstances() == null || getInformativeInstances().isEmpty()) {
        setInformativeInstances(newInformativeInstances());
    }

    File keep = new File(getInformativeInstances());
    keep.getParentFile().mkdirs();

    try {
        writer = Files.newBufferedWriter(new File(getInformativeInstances()).toPath(), Charset.defaultCharset(),
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);

    } catch (IOException ex) {
        Logger.getLogger(RealScenarioListener.class.getName()).log(Level.SEVERE, null, ex);
    }

    ///////////////////////////////////
    System.out.println(
            "\nWelcome to the real scenario listener. You can use it to obtain the most informative unlabeled data."
                    + "\nAt the end of this session you can save the labeled data for further analysis."
                    + "\nYou must specify in the configuration file the parameter <informative-instances> for setting the path where the "
                    + "instances that were labeled will be saved."
                    + "\nThis example of real-world use can be combined with a simulated or a human oracle."
                    + "\nThe labeled instances will be stored sequentially in: " + getInformativeInstances()
                    + "." + "\nIf you are ready to begin please press <enter>.");

    readLine();

    System.out.println("Active Learning begins...");
}

From source file:cn.codepub.redis.directory.RedisLockFactory.java

@Override
public Lock obtainLock(@NonNull Directory dir, String lockName) throws IOException {
    if (!(dir instanceof RedisDirectory)) {
        throw new IllegalArgumentException("Expect argument of type [" + RedisDirectory.class.getName() + "]!");
    }// w w  w .jav  a2s .  c o m
    Path lockFile = lockFileDirectory.resolve(lockName);
    try {
        Files.createFile(lockFile);
        log.debug("Lock file path = {}", lockFile.toFile().getAbsolutePath());
    } catch (IOException ignore) {
        //ignore
        log.debug("Lock file already exists!");
    }
    final Path realPath = lockFile.toRealPath();
    final FileTime creationTime = Files.readAttributes(realPath, BasicFileAttributes.class).creationTime();
    if (LOCK_HELD.add(realPath.toString())) {
        FileChannel fileChannel = null;
        FileLock lock = null;
        try {
            fileChannel = FileChannel.open(realPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
            lock = fileChannel.tryLock();
            if (lock != null) {
                return new RedisLock(lock, fileChannel, realPath, creationTime);
            } else {
                throw new LockObtainFailedException("Lock held by another program: " + realPath);
            }
        } finally {
            if (lock == null) {
                IOUtils.closeQuietly(fileChannel);
                clearLockHeld(realPath);
            }
        }
    } else {
        throw new LockObtainFailedException("Lock held by this virtual machine: " + realPath);
    }
}