Example usage for java.nio.file StandardOpenOption TRUNCATE_EXISTING

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

Introduction

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

Prototype

StandardOpenOption TRUNCATE_EXISTING

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

Click Source Link

Document

If the file already exists and it is opened for #WRITE access, then its length is truncated to 0.

Usage

From source file:com.scaniatv.LangFileUpdater.java

/**
 * Method that updates a custom lang file.
 * /* ww w. j  a  va2s  .  co  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:net.radai.confusion.spring.SpringAnnotationConfigTest.java

@Test
public void testSpringAnnotationIntegration() throws Exception {
    Path dir = Files.createTempDirectory("test");
    Path targetFile = dir.resolve("confFile");
    try (InputStream is = getClass().getClassLoader().getResourceAsStream("cats.ini");
            OutputStream os = Files.newOutputStream(targetFile, StandardOpenOption.WRITE,
                    StandardOpenOption.CREATE_NEW)) {
        ByteStreams.copy(is, os);//from w  w w .  j a  va2  s .c o  m
    }
    String absolutePath = targetFile.toFile().getCanonicalPath();
    System.setProperty("confFile", absolutePath);
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("annotationSpringContext.xml");
    //noinspection unchecked
    SpringAwareConfigurationService<Cats> confService = (SpringAwareConfigurationService<Cats>) context
            .getBean(ConfigurationService.class);
    Jsr330AnnotatedConfigurationConsumerBean consumer = context
            .getBean(Jsr330AnnotatedConfigurationConsumerBean.class);
    //noinspection unchecked
    Assert.assertNotNull(consumer.getConfService());
    Assert.assertNotNull(consumer.getInitialConf());
    Assert.assertTrue(consumer.getCats().isEmpty());

    try (InputStream is = getClass().getClassLoader().getResourceAsStream("cat.ini");
            OutputStream os = Files.newOutputStream(targetFile, StandardOpenOption.WRITE,
                    StandardOpenOption.TRUNCATE_EXISTING)) {
        ByteStreams.copy(is, os);
    }
    Thread.sleep(100);

    //verify event was received
    Assert.assertEquals(1, consumer.getCats().size());
    Assert.assertTrue(consumer.getInitialConf() != consumer.getCats().get(0));
    Assert.assertTrue(confService.getConfiguration() == consumer.getCats().get(0));

    context.close();
}

From source file:net.kemitix.checkstyle.ruleset.builder.ReadmeWriter.java

@Override
public void run(final String... args) throws Exception {
    final String readmeTemplate = readFile(templateProperties.getReadmeTemplate());
    final String enabledCheckstyle = readmeRules(this::isEnabledCheckstyleRule);
    final String enabledSevntu = readmeRules(this::isEnabledSevntuRule);
    final String disabledCheckstyle = readmeRules(this::isDisabledCheckstyleRule);
    final String disabledSevntu = readmeRules(this::isDisabledSevntuRule);
    final byte[] readme = String.format(readmeTemplate, indexBuilder.build(), enabledCheckstyle, enabledSevntu,
            disabledCheckstyle, disabledSevntu).getBytes(StandardCharsets.UTF_8);
    Files.write(outputProperties.getReadme(), readme, StandardOpenOption.TRUNCATE_EXISTING);
}

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/* w  ww  .ja  va  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:io.confluent.rest.SaslTest.java

@Before
public void setUp() throws Exception {
    jaasFile = File.createTempFile("jaas", ".config");
    loginPropertiesFile = File.createTempFile("login", ".properties");

    String jaas = "c3 {\n" + "  org.eclipse.jetty.jaas.spi.PropertyFileLoginModule required\n"
            + "  debug=\"true\"\n" + "  file=\"" + loginPropertiesFile.getAbsolutePath() + "\";\n" + "};\n";
    Files.write(jaasFile.toPath(), jaas.getBytes(StandardCharsets.UTF_8), StandardOpenOption.TRUNCATE_EXISTING);

    String loginProperties = "jay: kafka,Administrators\n" + "neha: akfak,Administrators\n" + "jun: kafka-\n";
    Files.write(loginPropertiesFile.toPath(), loginProperties.getBytes(StandardCharsets.UTF_8),
            StandardOpenOption.TRUNCATE_EXISTING);
    previousAuthConfig = System.getProperty("java.security.auth.login.config");
    Configuration.setConfiguration(null);
    System.setProperty("java.security.auth.login.config", jaasFile.getAbsolutePath());
    httpclient = HttpClients.createDefault();
    TestMetricsReporter.reset();/* ww w .j a v a 2 s  . c  om*/
    Properties props = new Properties();
    props.put(RestConfig.LISTENERS_CONFIG, httpUri);
    props.put(RestConfig.METRICS_REPORTER_CLASSES_CONFIG, "io.confluent.rest.TestMetricsReporter");
    configBasic(props);
    TestRestConfig config = new TestRestConfig(props);
    app = new SaslTestApplication(config);
    app.start();
}

From source file:org.sakuli.services.forwarder.checkmk.CheckMKResultServiceImpl.java

private void writeToFile(Path file, String output) throws SakuliForwarderException {
    try {/*  ww  w.j  av a 2 s  . co m*/
        logger.info(String.format("Write file to '%s'", file));
        Files.write(file, output.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException e) {
        throw new SakuliForwarderException(e, String.format(
                "Unexpected error by writing the output for check_mk to the following file '%s'", file));
    }
}

From source file:org.eclipse.packagedrone.utils.rpm.build.PayloadRecorder.java

public PayloadRecorder(final boolean autoFinish) throws IOException {
    this.autoFinish = autoFinish;

    this.tempFile = Files.createTempFile("rpm-", null);

    try {//from w w  w  .ja v a  2  s  .  c  o m
        this.fileStream = new BufferedOutputStream(Files.newOutputStream(this.tempFile,
                StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING));

        this.payloadCounter = new CountingOutputStream(this.fileStream);

        final GZIPOutputStream payloadStream = new GZIPOutputStream(this.payloadCounter);
        this.archiveCounter = new CountingOutputStream(payloadStream);

        // setup archive stream

        this.archiveStream = new CpioArchiveOutputStream(this.archiveCounter, CpioConstants.FORMAT_NEW, 4,
                "UTF-8");
    } catch (final IOException e) {
        Files.deleteIfExists(this.tempFile);
        throw e;
    }
}

From source file:org.basinmc.maven.plugins.minecraft.launcher.DownloadDescriptor.java

/**
 * Fetches the artifact from the server and stores it in a specified file.
 *//* www .  j a  v  a  2s . com*/
public void fetch(@Nonnull Path outputFile) throws IOException {
    HttpClient client = HttpClients.createMinimal();

    try {
        HttpGet request = new HttpGet(this.url.toURI());
        HttpResponse response = client.execute(request);

        StatusLine line = response.getStatusLine();

        if (line.getStatusCode() != 200) {
            throw new IOException(
                    "Unexpected status code: " + line.getStatusCode() + " - " + line.getReasonPhrase());
        }

        try (InputStream inputStream = response.getEntity().getContent()) {
            try (FileChannel fileChannel = FileChannel.open(outputFile, StandardOpenOption.CREATE,
                    StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
                try (ReadableByteChannel inputChannel = Channels.newChannel(inputStream)) {
                    fileChannel.transferFrom(inputChannel, 0, Long.MAX_VALUE);
                }
            }
        }
    } catch (URISyntaxException ex) {
        throw new IOException("Received invalid URI from API: " + ex.getMessage(), ex);
    }
}

From source file:divconq.util.IOUtil.java

public static OperationResult saveEntireFile(Path dest, String content) {
    OperationResult or = new OperationResult();

    try {//from  www . jav  a2 s  . c o m
        Files.createDirectories(dest.getParent());
        Files.write(dest, Utf8Encoder.encode(content), StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE, StandardOpenOption.SYNC);
    } catch (Exception x) {
        or.error(1, "Error saving file contents: " + x);
    }

    return or;
}

From source file:net.radai.confusion.spring.SpringXmlConfTest.java

@Test
public void testSpringXmlIntegration() throws Exception {
    Path dir = Files.createTempDirectory("test");
    Path targetFile = dir.resolve("confFile");
    try (InputStream is = getClass().getClassLoader().getResourceAsStream("cats.ini");
            OutputStream os = Files.newOutputStream(targetFile, StandardOpenOption.WRITE,
                    StandardOpenOption.CREATE_NEW)) {
        ByteStreams.copy(is, os);//from  ww w . j  a  v  a2 s . c  o m
    }
    String absolutePath = targetFile.toFile().getCanonicalPath();
    System.setProperty("confFile", absolutePath);
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("xmlSpringContext.xml");
    //noinspection unchecked
    SpringAwareConfigurationService<Cats> confService = (SpringAwareConfigurationService<Cats>) context
            .getBean(ConfigurationService.class);
    TraditionalConfigurationConsumerBean consumer = context.getBean(TraditionalConfigurationConsumerBean.class);
    //noinspection unchecked
    SimpleConfigurationService<Cats> delegate = (SimpleConfigurationService<Cats>) ReflectionTestUtils
            .getField(confService, "delegate");
    Assert.assertNotNull(confService.getConfiguration());
    Assert.assertTrue(delegate.isStarted());
    Assert.assertTrue(consumer.getConf() == confService.getConfiguration());
    Assert.assertTrue(consumer.getConfService() == confService);
    Assert.assertTrue(consumer.getCats().isEmpty());

    try (InputStream is = getClass().getClassLoader().getResourceAsStream("cat.ini");
            OutputStream os = Files.newOutputStream(targetFile, StandardOpenOption.WRITE,
                    StandardOpenOption.TRUNCATE_EXISTING)) {
        ByteStreams.copy(is, os);
    }
    Thread.sleep(100);

    //verify event was received
    Assert.assertEquals(1, consumer.getCats().size());
    Assert.assertTrue(consumer.getConf() != consumer.getCats().get(0));
    Assert.assertTrue(confService.getConfiguration() == consumer.getCats().get(0));

    context.close();
    Assert.assertFalse(delegate.isStarted());
}