Java Code Examples for java.nio.file.Files#newBufferedWriter()

The following examples show how to use java.nio.file.Files#newBufferedWriter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AuthorityAnalysis.java    From metadata-qa-marc with GNU General Public License v3.0 6 votes vote down vote up
private void printAuthoritiesSubfieldsStatistics() {
  Path path = Paths.get(parameters.getOutputDir(), "authorities-by-schema-subfields.csv");
  try (BufferedWriter writer = Files.newBufferedWriter(path)) {
    // final List<String> header = Arrays.asList("field", "location", "label", "abbreviation", "subfields", "scount");
    final List<String> header = Arrays.asList("id", "subfields", "count");
    writer.write(createRow(header));
    statistics.getSubfields()
      .entrySet()
      .stream()
      .sorted((e1, e2) ->
        e1.getKey().getField().compareTo(e2.getKey().getField()))
      .forEach(
        schemaEntry -> printSingleSchemaSubfieldsStatistics(writer, schemaEntry)
      );
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 2
Source File: FileVoteCache.java    From NuVotifier with GNU General Public License v3.0 6 votes vote down vote up
public void save() throws IOException {
    JsonObject votesObject = new JsonObject();

    cacheLock.lock();
    try {
        votesObject.addProperty("version", 2);
        votesObject.add("players", serializeMap(playerVoteCache));
        votesObject.add("servers", serializeMap(voteCache));
    } finally {
        cacheLock.unlock();
    }

    try (BufferedWriter writer = Files.newBufferedWriter(cacheFile.toPath(), StandardCharsets.UTF_8)) {
        GsonInst.gson.toJson(votesObject, writer);
    }
}
 
Example 3
Source File: TracingListener.java    From grappa with Apache License 2.0 6 votes vote down vote up
private void copyParseInfo(final FileSystem zipfs)
    throws IOException
{
    final Path path = zipfs.getPath(INFO_PATH);
    try (

        final BufferedWriter writer = Files.newBufferedWriter(path, UTF_8);
    ) {
        sb.setLength(0);
        sb.append(startTime).append(';')
            .append(prematchIndices.size()).append(';')
            .append(nextMatcherId).append(';')
            .append(nrLines).append(';')
            .append(nrChars).append(';')
            .append(nrCodePoints).append(';')
            .append(nextNodeId).append('\n');
        writer.append(sb);
        writer.flush();
    }
}
 
Example 4
Source File: YarnTwillPreparer.java    From twill with Apache License 2.0 6 votes vote down vote up
private JvmOptions saveJvmOptions(final Path targetPath) throws IOException {
  // Append runnable specific extra options.
  Map<String, String> runnableExtraOptions = Maps.newHashMap(
    Maps.transformValues(this.runnableExtraOptions, new Function<String, String>() {
      @Override
      public String apply(String options) {
        return addClassLoaderClassName(extraOptions.isEmpty() ? options : extraOptions + " " + options);
      }
    }));

  String globalOptions = addClassLoaderClassName(extraOptions);
  JvmOptions jvmOptions = new JvmOptions(globalOptions, runnableExtraOptions, debugOptions);
  if (globalOptions.isEmpty() && runnableExtraOptions.isEmpty()
    && JvmOptions.DebugOptions.NO_DEBUG.equals(debugOptions)) {
    // If no vm options, no need to localize the file.
    return jvmOptions;
  }

  LOG.debug("Creating {}", targetPath);
  try (Writer writer = Files.newBufferedWriter(targetPath, StandardCharsets.UTF_8)) {
    new Gson().toJson(new JvmOptions(globalOptions, runnableExtraOptions, debugOptions), writer);
  }
  LOG.debug("Done {}", targetPath);
  return jvmOptions;
}
 
Example 5
Source File: TargetsStressRunnerTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void throwsExceptionIfDifferenceIsFound()
    throws IOException, ParseException, TargetsStressRunException, MaxDifferencesException {

  Path file1 = temporaryPaths.newFile("1");
  Path file2 = temporaryPaths.newFile("2");
  Path file3 = temporaryPaths.newFile("3");

  expectedException.expect(TargetsStressRunException.class);
  expectedException.expectMessage(
      String.format(
          "Found differences between %s and %s", file1.toAbsolutePath(), file3.toAbsolutePath()));

  try (BufferedWriter output1 = Files.newBufferedWriter(file1);
      BufferedWriter output2 = Files.newBufferedWriter(file2);
      BufferedWriter output3 = Files.newBufferedWriter(file3)) {
    output1.write("//:target1 32bbfed4bbbb971d9499b016df1d4358cc4ad4ba");
    output2.write("//:target1 32bbfed4bbbb971d9499b016df1d4358cc4ad4ba");
    output3.write("//:target1 32bbfed4bbbb971d9499b016df1d4358cc4ad4ba");
    output1.newLine();
    output2.newLine();
    output3.newLine();

    output1.write("//:target2 81643a1508128186137c6b03d13b6352d6c5dfaf");
    output2.write("//:target2 81643a1508128186137c6b03d13b6352d6c5dfaf");
    output3.write("//:target2 a59619898666a2d5b3e1669a4293301b799763c1");
    output1.newLine();
    output2.newLine();
    output3.newLine();
  }

  TargetsStressRunner runner =
      new TargetsStressRunner(
          differFactory,
          Optional.of("python"),
          tempBinPath.toAbsolutePath().toString(),
          ImmutableList.of("-c", "config=value"),
          ImmutableList.of("//:target1", "//:target2"));
  runner.verifyNoChanges(file1, ImmutableList.of(file2, file3));
}
 
Example 6
Source File: FileDownloadTest.java    From pf4j-update with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws IOException {
    downloader = new SimpleFileDownloader();
    webserver = new WebServer();
    updateRepoDir = Files.createTempDirectory("repo");
    updateRepoDir.toFile().deleteOnExit();
    repoFile = Files.createFile(updateRepoDir.resolve("myfile"));
    BufferedWriter writer = new BufferedWriter(Files.newBufferedWriter(repoFile, Charset.forName("utf-8"), StandardOpenOption.APPEND));
    writer.write("test");
    writer.close();
    emptyFile = Files.createFile(updateRepoDir.resolve("emptyFile"));
}
 
Example 7
Source File: ShortIdDictionary.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
public void write(Path file) throws IOException {
    try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
        for (Map.Entry<String, String> e : map.entrySet()) {
            writer.write(e.getKey());
            writer.write(";");
            writer.write(e.getValue());
            writer.newLine();
        }
    }
}
 
Example 8
Source File: LinkGeometryExporter.java    From pt2matsim with GNU General Public License v2.0 5 votes vote down vote up
public void writeToFile(Path outputPath) throws IOException {
	try (BufferedWriter writer = Files.newBufferedWriter(outputPath)) {
		writer.write("LinkId" + SEPARATOR + "Geometry\n");
		for (Entry<Id<Link>, LinkDefinition> entry : linkDefinitions.entrySet()) {
			Optional<String> wkt = toWkt(entry.getValue());
			if (wkt.isPresent()) {
				writer.write(String.format("%s%s\"%s\"\n", entry.getKey(), SEPARATOR, wkt.get()));
			}
		}
	}
}
 
Example 9
Source File: CreateSymbolsTestImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void testGenerate(Path jar7, Path jar8, Path descDest, String version, String classDest) throws IOException {
    deleteRecursively(descDest);

    List<VersionDescription> versions =
            Arrays.asList(new VersionDescription(jar7.toAbsolutePath().toString(), "7", null),
                          new VersionDescription(jar8.toAbsolutePath().toString(), "8", "7"));

    ExcludeIncludeList acceptAll = new ExcludeIncludeList(null, null) {
        @Override public boolean accepts(String className) {
            return true;
        }
    };
    new CreateSymbols() {
        @Override
        protected boolean includeEffectiveAccess(ClassList classes, ClassDescription clazz) {
            return includeAll ? true : super.includeEffectiveAccess(classes, clazz);
        }
    }.createBaseLine(versions, acceptAll, descDest, null);
    Path symbolsDesc = descDest.resolve("symbols");
    try (Writer symbolsFile = Files.newBufferedWriter(symbolsDesc)) {
        symbolsFile.write("generate platforms 7:8");
        symbolsFile.write(System.lineSeparator());
        symbolsFile.write("platform version 7 files java.base-7.sym.txt");
        symbolsFile.write(System.lineSeparator());
        symbolsFile.write("platform version 8 base 7 files java.base-8.sym.txt");
        symbolsFile.write(System.lineSeparator());
    }
    new CreateSymbols().createSymbols(symbolsDesc.toAbsolutePath().toString(), classDest, CtSymKind.JOINED_VERSIONS);
}
 
Example 10
Source File: RollingFileWriter.java    From swage with Apache License 2.0 5 votes vote down vote up
/**
 * If necessary, close the current logfile and open a new one,
 * updating {@link #writer}.
 */
private void rollIfNeeded() throws IOException {
    // Do not roll unless record is complete, as indicated by flush
    if (!flushed) return;
    flushed = false;

    // If we have not yet passed the roll over mark do nothing
    Instant now = Instant.now();
    if (now.isBefore(rollAt)) {
        return;
    }

    // New file time, may not be the rollAt time if one or more intervals
    // have passed without anything being written
    Instant rollTime = now.truncatedTo(rollInterval);

    // Determine the name of the file that will be written to
    String name = this.baseName + format.format(LocalDateTime.ofInstant(rollTime, timeZone));
    this.outPath = this.directory.resolve(name);

    // Finish writing to previous log
    if (writer != null) {
        writer.flush();
        writer.close();
    }

    // Ensure the parent directory always exists, even if it was removed out from under us.
    // A no-op if the directory already exists.
    Files.createDirectories(outPath.getParent());

    // Create new file, set it as our write destination
    writer = Files.newBufferedWriter(
                outPath,
                StandardCharsets.UTF_8,
                StandardOpenOption.CREATE,
                StandardOpenOption.APPEND);

    // Point to the next time we want to roll the log, update rollAt
    this.rollAt = rollTime.plus(1, rollInterval);
}
 
Example 11
Source File: TimeSeriesTable.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
private static BufferedWriter createWriter(Path file) throws IOException {
    if (file.getFileName().toString().endsWith(".gz")) {
        return new BufferedWriter(new OutputStreamWriter(new GZIPOutputStream(Files.newOutputStream(file)), StandardCharsets.UTF_8));
    } else {
        return Files.newBufferedWriter(file, StandardCharsets.UTF_8);
    }
}
 
Example 12
Source File: TableReaderUnitTest.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Path createTestInputonPath(final Path path, final String... lines) throws IOException {
    try (final PrintWriter testWriter = new PrintWriter(Files.newBufferedWriter(path))) {
        for (final String line : lines) {
            testWriter.println(line);
        }
    }
    return path;
}
 
Example 13
Source File: ResourceLinker.java    From bazel with Apache License 2.0 5 votes vote down vote up
private Path extractPackages(CompiledResources compiled) throws IOException {
  Path packages = workingDirectory.resolve("packages");
  try (BufferedWriter writer = Files.newBufferedWriter(packages, StandardOpenOption.CREATE_NEW)) {
    for (CompiledResources resources : FluentIterable.from(include).append(compiled)) {
      writer.append(VariantConfiguration.getManifestPackage(resources.getManifest().toFile()));
      writer.newLine();
    }
  }
  return packages;
}
 
Example 14
Source File: FileUuidCache.java    From LuckPerms with MIT License 5 votes vote down vote up
public void save(Path file) {
    try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
        writer.write("# LuckPerms UUID lookup cache");
        writer.newLine();
        for (Map.Entry<UUID, String> ent : this.lookupMap.entrySet()) {
            String out = ent.getKey() + ":" + ent.getValue();
            writer.write(out);
            writer.newLine();
        }
        writer.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 15
Source File: WriteableUserPath.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public WriteableUserPath(Path path) throws IOException {
    controlContext = AccessController.getContext();
    // verify that the path is writeable
    if (Files.exists(path) && !Files.isWritable(path)) {
        // throw same type of exception as FileOutputStream
        // constructor, if file can't be opened.
        throw new FileNotFoundException("Could not write to file: " + path.toAbsolutePath());
    }
    // will throw if non-writeable
    BufferedWriter fw = Files.newBufferedWriter(path);
    fw.close();
    this.original = path;
    this.real = path.toRealPath();
    this.text = real.toString();
}
 
Example 16
Source File: CreateI18NKeysForConnectionHandler.java    From rapidminer-studio with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Writes all properties to the given {@code newPath} after reading in {@code backupPath}. Adds all connection
 * related keys in one block which might be appended to the end of the file if it did not exist before. Will keep
 * an existing block in the same space and expand on it. Also will remove all keys that are outside of that block.
 *
 * @param namespace
 * 		the namespace of the affected handlers
 * @param connectionPropertyValues
 * 		the key/value pair lines, in blocks and sorted
 * @param backupPath
 * 		the original file to expand on
 * @param newPath
 * 		the new file to write to
 * @throws IOException
 * 		if an I/O error occurs
 * @see #writeProperties(BufferedWriter, Map)
 */
private static void writeProperties(String namespace, Map<String, List<List<String>>> connectionPropertyValues,
									Path backupPath, Path newPath) throws IOException {
	String[] prefixes = Stream.of(TYPE_PREFIX, GROUP_PREFIX, PARAMETER_PREFIX)
			.map(p -> p + '.' + namespace).toArray(String[]::new);
	try (BufferedReader reader = Files.newBufferedReader(backupPath);
		 BufferedWriter writer = Files.newBufferedWriter(newPath, CREATE, TRUNCATE_EXISTING)) {
		int status = 0;
		String line;
		while ((line = reader.readLine()) != null) {
			switch (status) {
				case 0:
					if (StringUtils.startsWithAny(line, prefixes)) {
						// skip connection keys that are not collected in the proper area
						// they will be added again later
						break;
					}
					writer.write(line);
					writer.newLine();
					if (line.equals(CONNECTION_HEADER)) {
						status = 1;
					}
					break;
				case 1:
					writer.write(line);
					writer.newLine();
					writeProperties(writer, connectionPropertyValues);
					while ((line = reader.readLine()) != null && !line.startsWith("##")) {
						//skip existing connection entries
					}
					if (line != null) {
						writer.newLine();
						writer.write(line);
						writer.newLine();
					}
					status = 2;
					break;
				case 2:
					writer.write(line);
					writer.newLine();
					break;
				default:
					break;
			}
		}
		if (status == 0) {
			// no connections so far, append it all
			writer.newLine();
			writer.write(HEADER_LINE);
			writer.newLine();
			writer.write(CONNECTION_HEADER);
			writer.newLine();
			writer.write(HEADER_LINE);
			writer.newLine();
			writeProperties(writer, connectionPropertyValues);
		}
	}
}
 
Example 17
Source File: GroovyDslContingenciesProviderTest.java    From powsybl-core with Mozilla Public License 2.0 4 votes vote down vote up
private void writeToDslFile(String... lines) throws IOException {
    try (Writer writer = Files.newBufferedWriter(dslFile, StandardCharsets.UTF_8)) {
        writer.write(String.join(System.lineSeparator(), lines));
    }
}
 
Example 18
Source File: TextTemplate.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * @param exportTo The path to save to.
 * @param template The template to use.
 * @return {@code true} on success.
 */
public boolean export(Path exportTo, Path template) {
    try {
        char[]        buffer           = new char[1];
        boolean       lookForKeyMarker = true;
        StringBuilder keyBuffer        = new StringBuilder();
        try (BufferedReader in = Files.newBufferedReader(template, StandardCharsets.UTF_8)) {
            try (BufferedWriter out = Files.newBufferedWriter(exportTo, StandardCharsets.UTF_8)) {
                while (in.read(buffer) != -1) {
                    char ch = buffer[0];
                    if (lookForKeyMarker) {
                        if (ch == '@') {
                            lookForKeyMarker = false;
                            in.mark(1);
                        } else {
                            out.append(ch);
                        }
                    } else {
                        if (ch == '_' || Character.isLetterOrDigit(ch)) {
                            keyBuffer.append(ch);
                            in.mark(1);
                        } else {
                            if (!mEnhancedKeyParsing || ch != '@') {
                                in.reset();        // Allow KEYs to be surrounded by @KEY@
                            }
                            emitKey(in, out, keyBuffer.toString(), exportTo);
                            keyBuffer.setLength(0);
                            lookForKeyMarker = true;
                        }
                    }
                }
                if (keyBuffer.length() != 0) {
                    emitKey(in, out, keyBuffer.toString(), exportTo);
                }
            }
        }
        return true;
    } catch (Exception exception) {
        return false;
    }
}
 
Example 19
Source File: Networks.java    From powsybl-core with Mozilla Public License 2.0 4 votes vote down vote up
public static void dumpVariantId(Path workingDir, String variantId) throws IOException {
    try (BufferedWriter writer = Files.newBufferedWriter(workingDir.resolve("variant.txt"), StandardCharsets.UTF_8)) {
        writer.write(variantId);
        writer.newLine();
    }
}
 
Example 20
Source File: GolangOutputManager.java    From simple-binary-encoding with Apache License 2.0 3 votes vote down vote up
/**
 * Create a new output which will be a golang source file in the given package.
 * <p>
 * The {@link java.io.Writer} should be closed once the caller has finished with it. The Writer is
 * buffered for efficient IO operations.
 *
 * @param name the name of the golang class.
 * @return a {@link java.io.Writer} to which the source code should be written.
 * @throws IOException if an issue occurs when creating the file.
 */
public Writer createOutput(final String name) throws IOException
{
    final File targetFile = new File(outputDir, name + ".go");

    return Files.newBufferedWriter(targetFile.toPath(), StandardCharsets.UTF_8);
}