Example usage for java.nio.file Files write

List of usage examples for java.nio.file Files write

Introduction

In this page you can find the example usage for java.nio.file Files write.

Prototype

public static Path write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options)
        throws IOException 

Source Link

Document

Write lines of text to a file.

Usage

From source file:org.apache.bookkeeper.common.util.affinity.impl.IsolatedProcessors.java

/**
 * Instruct Linux to disable a particular CPU. This is used to disable hyper-threading on a particular core, by
 * shutting down the cpu that shares the same core.
 *//*w  w w.j  a  v a  2 s .  com*/
private static void changeCpuStatus(int cpu, boolean enable) throws IOException {
    Path cpuPath = Paths.get(String.format("/sys/devices/system/cpu/cpu%d/online", cpu));

    boolean currentState = Integer
            .parseInt(StringUtils.trim(new String(Files.readAllBytes(cpuPath), ENCODING))) != 0;

    if (currentState != enable) {
        Files.write(cpuPath, (enable ? "1\n" : "0\n").getBytes(ENCODING), StandardOpenOption.TRUNCATE_EXISTING);
        log.info("{} CPU {}", enable ? "Enabled" : "Disabled", cpu);
    }
}

From source file:org.trustedanalytics.servicebroker.hive.config.ExternalConfiguration.java

public String getKeyTabLocation() throws IOException {

    String keyTabFilePath = String.format("%s/%s.keytab", keyTabsDir,
            PrincipalNameNormalizer.create().normalize(getHiveSuperUser()));
    LOGGER.info("Trying to write keytab file" + keyTabFilePath);
    Path path = Paths.get(keyTabFilePath);
    if (Files.notExists(path)) {
        Files.write(path, Base64.getDecoder().decode(getHiveSuperUserKeyTab()), StandardOpenOption.CREATE_NEW);
    } else if (Files.isDirectory(path)) {
        throw new IOException(
                String.format("Under path %s exists directory. It's path where hive superuser keytab "
                        + "is stored. Please move or delete this directory", keyTabFilePath));
    }/*from  w w w .  j  a va  2  s  .  c  o  m*/
    return keyTabFilePath;
}

From source file:nlp.corpora.SwitchboardDialogueDB.java

/************************************************************************************
 * This method takes the converted data and
 * stores in a text file format which is required for the ChatBot.
 *///from   www  .j  ava 2s .co m
private void writeFile(List<String> rawData, String fileName, String folderName) {

    String addToFileName;
    String addToFolderName;
    String addToFilePath;
    Path addToFolderPath;
    try {
        addToFileName = StringUtils.substringBefore(FilenameUtils.getBaseName(fileName), ".");
        addToFolderName = folderName.substring(folderName.lastIndexOf("/") + 1);
        addToFolderPath = Paths.get(addToDirectory + "/" + addToFolderName + "_parsed/");
        Files.createDirectories(addToFolderPath);
        addToFilePath = addToFolderPath + "/" + addToFileName + "_parsed.txt";
        Path file = Paths.get(addToFilePath);
        Files.write(file, rawData, Charset.forName("UTF-8"));
    } catch (Exception ex) {
        System.out.println(ex.toString());
        System.out.println("writeFile() Method: Could not find the file");
    }
}

From source file:org.bonitasoft.web.designer.livebuild.WatcherTest.java

@Test
public void should_trigger_a_modified_event_when_a_file_is_modified() throws Exception {
    Path existingFile = Files.createFile(subDirectory.resolve("file"));
    PathListenerStub listener = new PathListenerStub();
    watcher.watch(folder.toPath(), listener);

    Files.write(existingFile, "hello".getBytes(), StandardOpenOption.APPEND);

    Thread.sleep(SLEEP_DELAY);/*from   w  w w.  j a  v a2s  .  c o m*/
    assertThat(listener.getChanged()).containsExactly(existingFile);
}

From source file:com.hortonworks.registries.util.HdfsFileStorageTest.java

@Test
public void testUploadJarWithDir() throws Exception {
    Map<String, String> config = new HashMap<>();
    config.put(HdfsFileStorage.CONFIG_FSURL, "file:///");
    config.put(HdfsFileStorage.CONFIG_DIRECTORY, HDFS_DIR);
    fileStorage.init(config);// www . ja v  a2s .c om

    File file = File.createTempFile("test", ".tmp");
    file.deleteOnExit();

    List<String> lines = Arrays.asList("test-line-1", "test-line-2");
    Files.write(file.toPath(), lines, Charset.forName("UTF-8"));
    String jarFileName = "test.jar";

    fileStorage.deleteFile(jarFileName);

    fileStorage.uploadFile(new FileInputStream(file), jarFileName);

    InputStream inputStream = fileStorage.downloadFile(jarFileName);
    List<String> actual = IOUtils.readLines(inputStream);
    Assert.assertEquals(lines, actual);
}

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:com.liferay.ide.gradle.core.GradleProjectBuilder.java

public IStatus initBundle(IProject project, String bundleUrl, IProgressMonitor monitor) throws CoreException {
    String bundleUrlProperty = "\n\n" + LiferayWorkspaceUtil.LIFERAY_WORKSPACE_BUNDLE_URL + "=" + bundleUrl;

    IPath gradlePropertiesLocation = project.getFile("gradle.properties").getLocation();

    File gradlePropertiesFile = gradlePropertiesLocation.toFile();

    try {/*ww  w  .java2 s  . c  o  m*/
        Files.write(gradlePropertiesFile.toPath(), bundleUrlProperty.getBytes(), StandardOpenOption.APPEND);
    } catch (IOException ioe) {
        GradleCore.logError("Error append bundle url property", ioe);
    }

    _runGradleTask("initBundle", monitor);

    project.refreshLocal(IResource.DEPTH_INFINITE, monitor);

    return Status.OK_STATUS;
}

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();//w  ww .  j a v  a  2 s .c  o m
    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.fim.util.DosFilePermissionsTest.java

@Test
public void weCanSetPermissions() throws IOException {
    if (IS_OS_WINDOWS) {
        Path file = rootDir.resolve("file");
        Files.write(file, "file content".getBytes(), CREATE);

        assertWeCanSetPermissions(file, "A");
        assertWeCanSetPermissions(file, "HR");
        assertWeCanSetPermissions(file, "S");
    }/*from  ww w  .  j  av a  2 s  .  c o m*/
}

From source file:com.bhuwan.eventregistration.business.boundary.EventRegistrationResource.java

@POST
@Path("{id}")
public void saveEventData(@PathParam("id") String id, JsonObject eventData)
        throws IOException, URISyntaxException {
    String path = getClass().getClassLoader().getResource("/eventdata/").getPath();
    String filePath = path + id + ".json";
    while (new File(filePath).exists()) {
        int fileId = Integer.valueOf(id) + 1;
        filePath = (path + fileId) + ".json";
    }/*from   www.j a  va  2s. c o  m*/
    System.out.println(" filepath: " + filePath);
    Files.write(Paths.get(filePath), eventData.toString().getBytes(), StandardOpenOption.CREATE);
}