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.input;
018
019import java.io.BufferedInputStream;
020import java.io.InputStream;
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 GeometryInput} implementation for reading content from a file.
029 */
030public class FileGeometryInput extends AbstractGeometryIOMetadata
031    implements GeometryInput {
032
033    /** Input file. */
034    private final Path file;
035
036    /** Construct a new instance for reading from the given file.
037     * @param file input file
038     */
039    public FileGeometryInput(final Path file) {
040        this(file, null);
041    }
042
043    /** Construct a new instance for reading from the given file with the
044     * specific charset.
045     * @param file input file
046     * @param charset charset to use when reading from the input file
047     */
048    public FileGeometryInput(final Path file, final Charset charset) {
049        super(GeometryIOUtils.getFileName(file), charset);
050
051        this.file = file;
052    }
053
054    /** Get the input file.
055     * @return input file
056     */
057    public Path getFile() {
058        return file;
059    }
060
061    /** {@inheritDoc}
062     *
063     * <p>The returned input stream is buffered.</p>
064     */
065    @Override
066    public InputStream getInputStream() {
067        return GeometryIOUtils.getUnchecked(() -> new BufferedInputStream(Files.newInputStream(file)));
068    }
069
070    /** {@inheritDoc} */
071    @Override
072    public String toString() {
073        final StringBuilder sb = new StringBuilder();
074        sb.append(getClass().getSimpleName())
075            .append("[file= ")
076            .append(getFile())
077            .append(']');
078
079        return sb.toString();
080    }
081}