Benchmarks writing via {@link RandomAccessFile} with custom buffering via a byte array.

@param configuration
Configuration with target file
@throws IOException
Failed to write to target file
326391
@Benchmark
	@BenchmarkMode(Mode.AverageTime)
	public void byteArrayRandomAccessFile(final Configuration configuration) throws IOException {
		byte[] buffer = new byte[BUFFER_CAPACITY];
		int position = 0;

		try (RandomAccessFile file = new RandomAccessFile(configuration.file, "rw")) {
			for (long i = 0; i < LINES; ++i) {
				if (BUFFER_CAPACITY - position < DATA.length) {
					file.write(buffer, 0, position);
					position = 0;
				}

				if (BUFFER_CAPACITY < DATA.length) {
					file.write(DATA);
				} else {
					System.arraycopy(DATA, 0, buffer, position, DATA.length);
					position += DATA.length;
				}

			}

			if (position > 0) {
				file.write(buffer, 0, position);
			}
		}
	}
579104
public static void writeConfigFile(OutputStream outputStream, Class<?>[] classes, boolean sortClasses)
			throws SQLException, IOException {
		if (sortClasses) {
			// sort our class list to make the output more deterministic
			Class<?>[] sortedClasses = new Class<?>[classes.length];
			System.arraycopy(classes, 0, sortedClasses, 0, classes.length);
			Arrays.sort(sortedClasses, classComparator);
			classes = sortedClasses;
		}
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream), 4096);
		try {
			writeHeader(writer);
			for (Class<?> clazz : classes) {
				writeConfigForTable(writer, clazz, sortClasses);
			}
			// NOTE: done is here because this is public
			System.out.println("Done.");
		} finally {
			writer.close();
		}
	}
1235202
public static void writeConfigFile(String fileName, boolean sortClasses) throws SQLException, IOException {
		List<Class<?>> classList = new ArrayList<Class<?>>();
		findAnnotatedClasses(classList, new File("."), 0);
		writeConfigFile(fileName, classList.toArray(new Class[classList.size()]), sortClasses);
	}
114966
public Reader create(Reader input, String configuration, String defaultConfiguration) throws IOException {
    if(defaultConfiguration==null) {
      defaultConfiguration = defaultArgument;
    }
    if (configs != null && configs.size() > 0) {
      if (configuration == null && defaultConfiguration == null) {
        throw new IOException("no (default)configuration");
      } else if (configuration == null) {
        if (configs.get(defaultConfiguration) != null) {
          return create(input, configs.get(defaultConfiguration));
        } else {
          throw new IOException(
              "default configuration " + defaultConfiguration + " not available");
        }
      } else {
        MtasConfiguration config = configs.get(configuration);
        if (config == null) {
          if (defaultConfiguration != null) {
            if (configs.get(defaultConfiguration) != null) {
              return create(input, configs.get(defaultConfiguration));
            } else {
              throw new IOException("configuration " + configuration
                  + " not found and default configuration " + defaultConfiguration
                  + " not available");
            }
          } else {
            throw new IOException("configuration " + configuration
                + " not available and no default configuration");
          }
        } else {
          return create(input, config);
        }
      }
    } else if (config != null) {
      return create(input, config);
    } else {
      throw new IOException("no configuration");
    }

  }
950513
private void writeConf() throws IOException {
    for (int i = 0; i < mNumMasters; i++) {
      File confDir = new File(mWorkDir, "conf-master" + i);
      writeConfToFile(confDir, mMasterProperties.getOrDefault(i, new HashMap<>()));
    }
    for (int i = 0; i < mNumWorkers; i++) {
      File confDir = new File(mWorkDir, "conf-worker" + i);
      writeConfToFile(confDir, mWorkerProperties.getOrDefault(i, new HashMap<>()));
    }
  }
993998
public static void writeTokenToFile(Token<? extends TokenIdentifier> token, Path tokenFilePath,
      Configuration configuration) throws IOException {
    Credentials credentials = new Credentials();
    credentials.addToken(token.getService(), token);
    credentials.writeTokenStorageFile(tokenFilePath, configuration);
  }
813089
private static void initDefaultsFromConfiguration(Configuration configuration) {
		final long to = configuration.getLong(ConfigConstants.FS_STREAM_OPENING_TIMEOUT_KEY,
			ConfigConstants.DEFAULT_FS_STREAM_OPENING_TIMEOUT);
		if (to < 0) {
			LOG.error("Invalid timeout value for filesystem stream opening: " + to + ". Using default value of " +
				ConfigConstants.DEFAULT_FS_STREAM_OPENING_TIMEOUT);
			DEFAULT_OPENING_TIMEOUT = ConfigConstants.DEFAULT_FS_STREAM_OPENING_TIMEOUT;
		} else if (to == 0) {
			DEFAULT_OPENING_TIMEOUT = 300000; // 5 minutes
		} else {
			DEFAULT_OPENING_TIMEOUT = to;
		}
	}
782249
private static void writeFile(CyclicBarrier barrier, AtomicLong runtime, int count,
      AlluxioConfiguration alluxioConf)
      throws Exception {
    FileSystem fileSystem = FileSystem.Factory.create(alluxioConf);
    byte[] buffer = new byte[(int) Math.min(sFileSize, 4 * Constants.MB)];
    Arrays.fill(buffer, (byte) 'a');
    AlluxioURI path = filename(count);

    if (fileSystem.exists(path)) {
      fileSystem.delete(path);
    }

    barrier.await();
    long startTime = System.nanoTime();
    long bytesWritten = 0;
    try (FileOutStream outStream = fileSystem.createFile(path)) {
      while (bytesWritten < sFileSize) {
        outStream.write(buffer, 0, (int) Math.min(buffer.length, sFileSize - bytesWritten));
        bytesWritten += buffer.length;
      }
    }
    runtime.addAndGet(System.nanoTime() - startTime);
  }
260078
ByteBuffer writeView(int position, int needs) throws IOException
    {
        int waterMark = position+needs;
        if (waterMark > content.capacity())
        {
            if (refSet.containsKey(content))
            {
                throw new IOException("cannot grow file because of writable mapping for content. (non carbage collected mapping?)");
            }
            int blockSize = fileStore.getBlockSize();
            int newCapacity = Math.max(((waterMark / blockSize) + 1) * blockSize, 2*content.capacity());
            ByteBuffer newBB = ByteBuffer.allocateDirect(newCapacity);
            newBB.put(content);
            newBB.flip();
            content = newBB;
        }
        ByteBuffer bb = content.duplicate();
        refSet.add(content, bb);
        bb.limit(waterMark).position(position);
        return bb;
    }
979187
public static void writeInput(Configuration conf, Path inputDir) throws IOException {
        FileSystem fs = FileSystem.get(conf);

        if (fs.exists(inputDir)) {
            throw new IOException(String.format("Input directory '%s' exists - please remove and rerun this example", inputDir));
        }

        OutputStreamWriter writer = new OutputStreamWriter(fs.create(new Path(inputDir, "input.txt")));
        for (String name : EXAMPLE_NAMES) {
            writer.write(name);
        }
        IOUtils.closeStream(writer);
    }
1313931
public static void saveConfig (File target, Serializable config)
        throws IOException
    {
        FileOutputStream fout = new FileOutputStream(target);
        ObjectOutputStream oout = new ObjectOutputStream(fout);
        oout.writeObject(config);
        oout.close();
    }
977656
public static void writeFile(MapWriterConfiguration configuration, TileBasedDataProcessor dataProcessor)
            throws IOException {
        EXECUTOR_SERVICE = Executors.newFixedThreadPool(configuration.getThreads());
        RandomAccessFile randomAccessFile = new RandomAccessFile(configuration.getOutputFile(), "rw");

        int amountOfZoomIntervals = dataProcessor.getZoomIntervalConfiguration().getNumberOfZoomIntervals();
        ByteBuffer containerHeaderBuffer = ByteBuffer.allocate(HEADER_BUFFER_SIZE);
        // CONTAINER HEADER
        int totalHeaderSize = writeHeaderBuffer(configuration, dataProcessor, containerHeaderBuffer);

        // set to mark where zoomIntervalConfig starts
        containerHeaderBuffer.reset();

        final LoadingCache<TDWay, Geometry> jtsGeometryCache = CacheBuilder.newBuilder()
                .maximumSize(JTS_GEOMETRY_CACHE_SIZE).concurrencyLevel(Runtime.getRuntime().availableProcessors() * 2)
                .build(new JTSGeometryCacheLoader(dataProcessor));

        // SUB FILES
        // for each zoom interval write a sub file
        long currentFileSize = totalHeaderSize;
        for (int i = 0; i < amountOfZoomIntervals; i++) {
            // SUB FILE INDEX AND DATA
            long subfileSize = writeSubfile(currentFileSize, i, dataProcessor, jtsGeometryCache, randomAccessFile,
                    configuration);
            // SUB FILE META DATA IN CONTAINER HEADER
            writeSubfileMetaDataToContainerHeader(dataProcessor.getZoomIntervalConfiguration(), i, currentFileSize,
                    subfileSize, containerHeaderBuffer);
            currentFileSize += subfileSize;
        }

        randomAccessFile.seek(0);
        randomAccessFile.write(containerHeaderBuffer.array(), 0, totalHeaderSize);

        // WRITE FILE SIZE TO HEADER
        long fileSize = randomAccessFile.length();
        randomAccessFile.seek(OFFSET_FILE_SIZE);
        randomAccessFile.writeLong(fileSize);

        randomAccessFile.close();

        CacheStats stats = jtsGeometryCache.stats();
        LOGGER.fine("Tag values stats:\n" + OSMUtils.logValueTypeCount());
        LOGGER.info("JTS Geometry cache hit rate: " + stats.hitRate());
        LOGGER.info("JTS Geometry total load time: " + stats.totalLoadTime() / 1000);

        LOGGER.info("Finished writing file.");
    }
851367
public static void writeConfigFile(File configFile, Class<?>[] classes, boolean sortClasses)
			throws SQLException, IOException {
		System.out.println("Writing configurations to " + configFile.getAbsolutePath());
		writeConfigFile(new FileOutputStream(configFile), classes, sortClasses);
	}
101562
public static void generate(ConfigurationImpl configuration,
                                IndexBuilder indexbuilder) {
        SplitIndexWriter indexgen;
        DocPath filename = DocPath.empty;
        DocPath path = DocPaths.INDEX_FILES;
        try {
            Set<Object> keys = new TreeSet<>(Arrays.asList(indexbuilder.elements()));
            keys.addAll(configuration.tagSearchIndexKeys);
            List<Object> elements = new ArrayList<>(keys);
            ListIterator<Object> li = elements.listIterator();
            while (li.hasNext()) {
                Object ch = li.next();
                filename = DocPaths.indexN(li.nextIndex());
                indexgen = new SplitIndexWriter(configuration,
                        path.resolve(filename),
                        indexbuilder, elements, li.previousIndex(), li.nextIndex());
                indexgen.generateIndexFile((Character) ch);
                if (!li.hasNext()) {
                    indexgen.createSearchIndexFiles();
                }
                indexgen.close();
            }
        } catch (IOException exc) {
            configuration.standardmessage.error(
                        "doclet.exception_encountered",
                        exc.toString(), filename.getPath());
            throw new DocletAbortException(exc);
        }
    }
642222
public void write(Configuration config)
    throws IOException {

    pp.startDocument();
    pp.startElement("duke", null);

    // FIXME: here we should write the objects, but that's not
    // possible with the current API. we don't need that for the
    // genetic algorithm at the moment, but it would be useful.

    pp.startElement("schema", null);

    writeElement("threshold", "" + config.getThreshold());
    if (config.getMaybeThreshold() != 0.0)
      writeElement("maybe-threshold", "" + config.getMaybeThreshold());

    for (Property p : config.getProperties())
      writeProperty(p);

    pp.endElement("schema");

    String dbclass = config.getDatabase(false).getClass().getName();
    AttributeListImpl atts = new AttributeListImpl();
    atts.addAttribute("class", "CDATA", dbclass);
    pp.startElement("database", atts);
    pp.endElement("database");

    if (config.isDeduplicationMode())
      for (DataSource src : config.getDataSources())
        writeDataSource(src);
    else {
      pp.startElement("group", null);
      for (DataSource src : config.getDataSources(1))
        writeDataSource(src);
      pp.endElement("group");

      pp.startElement("group", null);
      for (DataSource src : config.getDataSources(2))
        writeDataSource(src);
      pp.endElement("group");
    }

    pp.endElement("duke");
    pp.endDocument();
  }
1182208
public void write(FsSettings settings) throws IOException {
        writeFile(settings.getName(), SETTINGS_YAML, FsSettingsParser.toYaml(settings));
    }
148759
@SuppressWarnings("unchecked")
    @Override
    public T readConfig(InputStream fileAsStream) throws ConfigurationException {
        InputStreamReader streamReader = new InputStreamReader(fileAsStream);
        try {
            YamlReader reader = new YamlReader(streamReader);
            reader.getConfig().setClassTag(clazz.getSimpleName(), clazz);
            return (T) reader.read();
        } catch (YamlException e) {
            throw new ConfigurationException("Configuration Exception", "CONF_002", e);
        }
    }