
br.com.objectos.flat.FlatFile Maven / Gradle / Ivy
/*
* Copyright 2016 Objectos, Fábrica de Software LTDA.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package br.com.objectos.flat;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.file.NoSuchFileException;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
import br.com.objectos.core.io.File;
import br.com.objectos.core.io.FileAppender;
import br.com.objectos.core.lang.Preconditions;
/**
* @author [email protected] (Marcio Endo)
*/
public class FlatFile {
private final File delegate;
private FlatFile(File delegate) {
this.delegate = Objects.requireNonNull(delegate);
}
public static FlatFile of(File file) {
return new FlatFile(file);
}
public FlatFile append(FlatWritable record) {
try (FlatWriter writer = appender()) {
record.writeTo(writer);
}
return this;
}
public void deleteUnchecked() {
delegate.deleteUnchecked();
}
public Optional readerAtLastRecord(int size) {
Preconditions.checkArgument(size > 0);
try {
long filesize = delegate.sizeChecked();
if (filesize == 0) {
return Optional.empty();
}
if (filesize < size) {
return Optional.empty();
}
long toSkip = filesize - (size + 1);
InputStream in = delegate.openStreamChecked();
in.skip(toSkip);
FlatReader reader = FlatReader.open(in);
return Optional.of(reader);
} catch (NoSuchFileException e) {
return Optional.empty();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public Stream stream() {
try {
InputStream in = delegate.openStreamChecked();
return FlatReader.open(in).stream();
} catch (NoSuchFileException e) {
return Stream.of();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private FlatWriter appender() {
FileAppender out = FileAppender.of(delegate);
return FlatWriter.of(out);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy