下面列出了java.nio.file.StandardOpenOption#APPEND 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void exportTo(final FlowFile flowFile, final Path path, final boolean append) {
validateState(flowFile);
if (flowFile == null || path == null) {
throw new IllegalArgumentException("argument cannot be null");
}
if (!(flowFile instanceof MockFlowFile)) {
throw new IllegalArgumentException("Cannot export a flow file that I did not create");
}
final MockFlowFile mock = (MockFlowFile) flowFile;
final OpenOption mode = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE;
try (final OutputStream out = Files.newOutputStream(path, mode)) {
out.write(mock.getData());
} catch (final IOException e) {
throw new FlowFileAccessException(e.toString(), e);
}
}
@Override
public long exportTo(final ContentClaim claim, final Path destination, final boolean append, final long offset, final long length) throws IOException {
if (claim == null) {
if (append) {
return 0L;
}
Files.createFile(destination);
return 0L;
}
final StandardOpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE;
try (final InputStream in = read(claim);
final OutputStream destinationStream = Files.newOutputStream(destination, openOption)) {
if (offset > 0) {
StreamUtils.skip(in, offset);
}
StreamUtils.copy(in, destinationStream, length);
return length;
}
}
/**
* 報告書をCSVファイルに書き込む
*
* @param path ファイル
* @param header ヘッダー
* @param body 内容
* @param applend 追記フラグ
* @throws IOException
*/
public static void writeCsv(Path path, String[] header, List<String[]> body, boolean applend)
throws IOException {
OpenOption[] options;
if (applend) {
options = new OpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.APPEND };
} else {
options = new OpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING };
}
try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(path, options))) {
if (!Files.exists(path) || (Files.size(path) <= 0)) {
out.write(StringUtils.join(header, ',').getBytes(AppConstants.CHARSET));
out.write("\r\n".getBytes(AppConstants.CHARSET));
}
for (String[] colums : body) {
out.write(StringUtils.join(colums, ',').getBytes(AppConstants.CHARSET));
out.write("\r\n".getBytes(AppConstants.CHARSET));
}
}
}
@Override
public void exportTo(FlowFile flowFile, final Path path, final boolean append) {
flowFile = validateState(flowFile);
if (flowFile == null || path == null) {
throw new IllegalArgumentException("argument cannot be null");
}
if (!(flowFile instanceof MockFlowFile)) {
throw new IllegalArgumentException("Cannot export a flow file that I did not create");
}
final MockFlowFile mock = (MockFlowFile) flowFile;
final OpenOption mode = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE;
try (final OutputStream out = Files.newOutputStream(path, mode)) {
out.write(mock.getData());
} catch (final IOException e) {
throw new FlowFileAccessException(e.toString(), e);
}
}
@Override
public void exportTo(FlowFile flowFile, final Path path, final boolean append) {
flowFile = validateState(flowFile);
if (flowFile == null || path == null) {
throw new IllegalArgumentException("argument cannot be null");
}
if (!(flowFile instanceof StatelessFlowFile)) {
throw new IllegalArgumentException("Cannot export a flow file that I did not create");
}
StatelessFlowFile statelessFlowFile = (StatelessFlowFile) flowFile;
final OpenOption mode = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE;
try (final OutputStream out = Files.newOutputStream(path, mode)) {
if (statelessFlowFile.materializeContent)
statelessFlowFile.materializeData();
copyTo(statelessFlowFile.getDataStream(), out);
} catch (final IOException e) {
throw new FlowFileAccessException(e.toString(), e);
}
}
@Override
public long exportTo(final ContentClaim claim, final Path destination, final boolean append, final long offset, final long length) throws IOException {
if (claim == null) {
if (append) {
return 0L;
}
Files.createFile(destination);
return 0L;
}
final StandardOpenOption openOption = append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE;
try (final InputStream in = read(claim);
final OutputStream destinationStream = Files.newOutputStream(destination, openOption)) {
if (offset > 0) {
StreamUtils.skip(in, offset);
}
StreamUtils.copy(in, destinationStream, length);
return length;
}
}
private void createCsvFile(File directory, CsvFileData csvData, boolean append) throws IOException
{
File file = new File(directory, csvData.getFileName());
boolean fileExists = file.exists();
OpenOption[] openOptions = append ? new OpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.APPEND }
: new OpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING };
try (Writer writer = new OutputStreamWriter(Files.newOutputStream(file.toPath(), openOptions),
StandardCharsets.UTF_8);
CSVPrinter printer = append && fileExists ? csvFormat.print(writer)
: csvFormat.withHeader(csvData.getHeader()).print(writer))
{
printer.printRecords(csvData.getData());
}
}
@Override
public void run(final RunNotifier notifier) {
super.run(notifier);
if (delta != 0)
return;
try {
final String className = getTestClass().getName();
final File manifestFile = getManifestFile();
manifestFile.getParentFile().mkdirs();
final Path path = manifestFile.toPath();
final OpenOption openOption;
if (Files.exists(path)) {
// Check if the test class name is mentioned in the manifest
try (final BufferedReader reader = new BufferedReader(new FileReader(manifestFile))) {
String line;
while ((line = reader.readLine()) != null)
if (line.equals(className))
return;
}
openOption = StandardOpenOption.APPEND;
}
else {
openOption = StandardOpenOption.CREATE;
}
// Add the test class name to the manifest
Files.write(path, (className + "\n").getBytes(), openOption);
}
catch (final IOException e) {
throw new IllegalStateException(e);
}
}
static OpenOptions forNewOutputStream(Collection<? extends OpenOption> options) {
if (options.isEmpty()) {
// CREATE, TRUNCATE_EXISTING and WRITE, i.e. create, not createNew, and not append
return new OpenOptions(false, true, false, true, false, false, Collections.<OpenOption>emptySet());
}
boolean append = false;
boolean truncateExisting = false;
boolean create = false;
boolean createNew = false;
boolean deleteOnClose = false;
for (OpenOption option : options) {
if (option == StandardOpenOption.APPEND) {
append = true;
} else if (option == StandardOpenOption.TRUNCATE_EXISTING) {
truncateExisting = true;
} else if (option == StandardOpenOption.CREATE) {
create = true;
} else if (option == StandardOpenOption.CREATE_NEW) {
createNew = true;
} else if (option == StandardOpenOption.DELETE_ON_CLOSE) {
deleteOnClose = true;
} else if (option != StandardOpenOption.WRITE && !isIgnoredOpenOption(option)) {
throw Messages.fileSystemProvider().unsupportedOpenOption(option);
}
}
// append and truncateExisting contradict each other
if (append && truncateExisting) {
throw Messages.fileSystemProvider().illegalOpenOptionCombination(options);
}
return new OpenOptions(false, true, append, create, createNew, deleteOnClose, options);
}
@Override
public void doWork() throws OperatorException {
File file = getParameterAsFile(PARAMETER_FILE, true);
String text = getParameterAsString(PARAMETER_TEXT);
String modeString = getParameterAsString(PARAMETER_MODE);
OpenOption mode = APPEND.equals(modeString) ? StandardOpenOption.APPEND : StandardOpenOption.TRUNCATE_EXISTING;
try {
Files.write(file.toPath(), Arrays.asList(text), Encoding.getEncoding(this), StandardOpenOption.CREATE, mode);
} catch (IOException e) {
throw new UserError(this, 303, file.getName(), e);
}
dummyPorts.passDataThrough();
}
static OpenOption[] getOpenOptions(boolean append) {
OpenOption[] defaultOpenOptions = {StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE};
OpenOption[] appendOpenOptions = {StandardOpenOption.APPEND, StandardOpenOption.WRITE};
return append ? appendOpenOptions : defaultOpenOptions;
}
/**
* Opens a file, returning an input stream to read from the file. This
* method works in exactly the manner specified by the {@link
* Files#newInputStream} method.
*
* <p> The default implementation of this method opens a channel to the file
* as if by invoking the {@link #newByteChannel} method and constructs a
* stream that reads bytes from the channel. This method should be overridden
* where appropriate.
*
* @param path
* the path to the file to open
* @param options
* options specifying how the file is opened
*
* @return a new input stream
*
* @throws IllegalArgumentException
* if an invalid combination of options is specified
* @throws UnsupportedOperationException
* if an unsupported option is specified
* @throws IOException
* if an I/O error occurs
* @throws SecurityException
* In the case of the default provider, and a security manager is
* installed, the {@link SecurityManager#checkRead(String) checkRead}
* method is invoked to check read access to the file.
*/
public InputStream newInputStream(Path path, OpenOption... options)
throws IOException
{
if (options.length > 0) {
for (OpenOption opt: options) {
// All OpenOption values except for APPEND and WRITE are allowed
if (opt == StandardOpenOption.APPEND ||
opt == StandardOpenOption.WRITE)
throw new UnsupportedOperationException("'" + opt + "' not allowed");
}
}
ReadableByteChannel rbc = Files.newByteChannel(path, options);
if (rbc instanceof FileChannelImpl) {
((FileChannelImpl) rbc).setUninterruptible();
}
return Channels.newInputStream(rbc);
}
static OpenOptions forNewByteChannel(Set<? extends OpenOption> options) {
boolean read = false;
boolean write = false;
boolean append = false;
boolean truncateExisting = false;
boolean create = false;
boolean createNew = false;
boolean deleteOnClose = false;
for (OpenOption option : options) {
if (option == StandardOpenOption.READ) {
read = true;
} else if (option == StandardOpenOption.WRITE) {
write = true;
} else if (option == StandardOpenOption.APPEND) {
append = true;
} else if (option == StandardOpenOption.TRUNCATE_EXISTING) {
truncateExisting = true;
} else if (option == StandardOpenOption.CREATE) {
create = true;
} else if (option == StandardOpenOption.CREATE_NEW) {
createNew = true;
} else if (option == StandardOpenOption.DELETE_ON_CLOSE) {
deleteOnClose = true;
} else if (!isIgnoredOpenOption(option)) {
throw Messages.fileSystemProvider().unsupportedOpenOption(option);
}
}
// as per Files.newByteChannel, if none of these options is given, default to read
if (!read && !write && !append) {
read = true;
}
// read contradicts with write, append, create and createNew; TRUNCATE_EXISTING is ignored in combination with READ
if (read && (write || append || create || createNew)) {
throw Messages.fileSystemProvider().illegalOpenOptionCombination(options);
}
// append and truncateExisting contract each other
if (append && truncateExisting) {
throw Messages.fileSystemProvider().illegalOpenOptionCombination(options);
}
// read and write contract each other; read and append contract each other; append and truncateExisting contract each other
if ((read && write) || (read && append) || (append && truncateExisting)) {
throw Messages.fileSystemProvider().illegalOpenOptionCombination(options);
}
return new OpenOptions(read, write, append, create, createNew, deleteOnClose, options);
}
public FileSerializationEventBusListener(Path outputPath) throws IOException {
super(
outputPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND);
}