001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.geometry.io.core.output; 018 019import java.io.BufferedOutputStream; 020import java.io.OutputStream; 021import java.nio.charset.Charset; 022import java.nio.file.Files; 023import java.nio.file.Path; 024 025import org.apache.commons.geometry.io.core.AbstractGeometryIOMetadata; 026import org.apache.commons.geometry.io.core.internal.GeometryIOUtils; 027 028/** {@link GeometryOutput} implementation for writing content to a file. 029 */ 030public class FileGeometryOutput extends AbstractGeometryIOMetadata 031 implements GeometryOutput { 032 033 /** File to write to. */ 034 private final Path file; 035 036 /** Construct a new instance with the given file and no charset. 037 * @param file output file 038 */ 039 public FileGeometryOutput(final Path file) { 040 this(file, null); 041 } 042 043 /** Construct a new instance with the given file and charset. 044 * @param file output file 045 * @param charset file charset 046 */ 047 public FileGeometryOutput(final Path file, final Charset charset) { 048 super(GeometryIOUtils.getFileName(file), charset); 049 050 this.file = file; 051 } 052 053 /** Get the output file. 054 * @return output file 055 */ 056 public Path getFile() { 057 return file; 058 } 059 060 /** {@inheritDoc} 061 * 062 * <p>The returned output stream is buffered.</p> 063 */ 064 @Override 065 public OutputStream getOutputStream() { 066 return GeometryIOUtils.getUnchecked(() -> new BufferedOutputStream(Files.newOutputStream(file))); 067 } 068 069 /** {@inheritDoc} */ 070 @Override 071 public String toString() { 072 final StringBuilder sb = new StringBuilder(); 073 sb.append(getClass().getSimpleName()) 074 .append("[file= ") 075 .append(getFile()) 076 .append(']'); 077 078 return sb.toString(); 079 } 080}