下面列出了java.nio.file.StandardOpenOption#TRUNCATE_EXISTING 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
static OpenOptions forNewInputStream(Collection<? extends OpenOption> options) {
if (options.isEmpty()) {
return new OpenOptions(true, false, false, false, false, false, Collections.<OpenOption>emptySet());
}
boolean deleteOnClose = false;
for (OpenOption option : options) {
if (option == StandardOpenOption.DELETE_ON_CLOSE) {
deleteOnClose = true;
} else if (option != StandardOpenOption.READ && option != StandardOpenOption.TRUNCATE_EXISTING && !isIgnoredOpenOption(option)) {
// TRUNCATE_EXISTING is ignored in combination with READ
throw Messages.fileSystemProvider().unsupportedOpenOption(option);
}
}
return new OpenOptions(true, false, false, false, false, deleteOnClose, options);
}
/**
* 報告書を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));
}
}
}
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());
}
}
public WebResource writeCustomized(String fileName, Supplier<WebResource> source) throws IOException {
WebResource original = source.get();
byte[] bytes = original.asBytes();
OpenOption[] overwrite = {StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE};
Path to = files.getCustomizationDirectory().resolve(fileName);
Files.createDirectories(to.getParent());
Files.write(to, bytes, overwrite);
return original;
}
@Override
public void writePage(String tableSpace, String tableName, long pageId, Collection<Record> newPage) throws DataStorageManagerException {
// synch on table is done by the TableManager
long _start = System.currentTimeMillis();
Path tableDir = getTableDirectory(tableSpace, tableName);
Path pageFile = getPageFile(tableDir, pageId);
long size;
try {
if (pageodirect) {
try (ODirectFileOutputStream odirect = new ODirectFileOutputStream(pageFile, O_DIRECT_BLOCK_BATCH,
StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
size = writePage(newPage, null, odirect);
}
} else {
try (ManagedFile file = ManagedFile.open(pageFile, requirefsync,
StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
SimpleBufferedOutputStream buffer = new SimpleBufferedOutputStream(file.getOutputStream(), COPY_BUFFERS_SIZE)) {
size = writePage(newPage, file, buffer);
}
}
} catch (IOException err) {
throw new DataStorageManagerException(err);
}
long now = System.currentTimeMillis();
long delta = (now - _start);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.log(Level.FINER, "writePage {0} KBytes,{1} records, time {2} ms", new Object[]{(size / 1024) + "", newPage.size(), delta + ""});
}
dataPageWrites.registerSuccessfulEvent(delta, TimeUnit.MILLISECONDS);
}
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);
}
@Nullable
private BufferedWriter initWriter() {
try {
StandardOpenOption openOption =
Files.exists(filePath)
? StandardOpenOption.TRUNCATE_EXISTING
: StandardOpenOption.CREATE_NEW;
return Files.newBufferedWriter(filePath, StandardCharsets.UTF_8, openOption);
} catch (IOException e) {
failed = true;
logger.atSevere().withCause(e).log(
"Could not open file: %s. Redirecting will be disabled.", filePath);
}
return null;
}
@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();
}
public void setOpenOptions ( final OpenOption[] openOptions )
{
// always create a new array so that the result is independent of the old array
if ( openOptions == null )
{
this.openOptions = new OpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING };
}
else
{
this.openOptions = Arrays.copyOf ( openOptions, openOptions.length );
}
}
/**
* Convert Java open options to native flags.
*
* @param modes java options.
* @param log logger.
* @param enableDirect flag for enabling option {@link IgniteNativeIoLib#O_DIRECT} .
* @return native flags for open method.
*/
private static int setupOpenFlags(OpenOption[] modes, IgniteLogger log, boolean enableDirect) {
int flags = enableDirect ? IgniteNativeIoLib.O_DIRECT : 0;
List<OpenOption> openOptionList = Arrays.asList(modes);
for (OpenOption mode : openOptionList) {
if (mode == StandardOpenOption.READ) {
flags |= openOptionList.contains(StandardOpenOption.WRITE)
? IgniteNativeIoLib.O_RDWR
: IgniteNativeIoLib.O_RDONLY;
}
else if (mode == StandardOpenOption.WRITE) {
flags |= openOptionList.contains(StandardOpenOption.READ)
? IgniteNativeIoLib.O_RDWR
: IgniteNativeIoLib.O_WRONLY;
}
else if (mode == StandardOpenOption.CREATE)
flags |= IgniteNativeIoLib.O_CREAT;
else if (mode == StandardOpenOption.TRUNCATE_EXISTING)
flags |= IgniteNativeIoLib.O_TRUNC;
else if (mode == StandardOpenOption.SYNC)
flags |= IgniteNativeIoLib.O_SYNC;
else
log.error("Unsupported open option [" + mode + "]");
}
return flags;
}
@Override
public void accept(
int fileIndex, ByteDataView data, Set<String> descriptors, DiagnosticsHandler handler) {
StandardOpenOption[] options = {
StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING
};
try (OutputStream stream = new BufferedOutputStream(Files.newOutputStream(output, options))) {
stream.write(data.getBuffer(), data.getOffset(), data.getLength());
} catch (IOException e) {
handler.error(new ExceptionDiagnostic(e, new PathOrigin(output)));
}
}
static OpenOption[] getOpenOptions(boolean append) {
OpenOption[] defaultOpenOptions = {StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE};
OpenOption[] appendOpenOptions = {StandardOpenOption.APPEND, StandardOpenOption.WRITE};
return append ? appendOpenOptions : defaultOpenOptions;
}
@Override
public void writeIndexPage(
String tableSpace, String indexName,
long pageId, DataWriter writer
) throws DataStorageManagerException {
long _start = System.currentTimeMillis();
Path tableDir = getIndexDirectory(tableSpace, indexName);
Path pageFile = getPageFile(tableDir, pageId);
long size;
try {
if (indexodirect) {
try (ODirectFileOutputStream odirect = new ODirectFileOutputStream(pageFile, O_DIRECT_BLOCK_BATCH,
StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
size = writeIndexPage(writer, null, odirect);
}
} else {
try (ManagedFile file = ManagedFile.open(pageFile, requirefsync,
StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
SimpleBufferedOutputStream buffer = new SimpleBufferedOutputStream(file.getOutputStream(), COPY_BUFFERS_SIZE)) {
size = writeIndexPage(writer, file, buffer);
}
}
} catch (IOException err) {
LOGGER.log(Level.SEVERE, "Failed to write on path: {0}", pageFile);
Path path = pageFile;
boolean exists;
do {
exists = Files.exists(path);
if (exists) {
LOGGER.log(Level.INFO,
"Path {0}: directory {1}, file {2}, link {3}, writable {4}, readable {5}, executable {6}",
new Object[] { path, Files.isDirectory(path), Files.isRegularFile(path),
Files.isSymbolicLink(path), Files.isWritable(path), Files.isReadable(path),
Files.isExecutable(path) });
} else {
LOGGER.log(Level.INFO, "Path {0} doesn't exists", path);
}
path = path.getParent();
} while (path != null && !exists);
throw new DataStorageManagerException(err);
}
long now = System.currentTimeMillis();
long delta = (now - _start);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.log(Level.FINER, "writePage {0} KBytes, time {2} ms", new Object[]{(size / 1024) + "", delta + ""});
}
indexPageWrites.registerSuccessfulEvent(delta, TimeUnit.MILLISECONDS);
}
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);
}
protected String extractTableOfContents(Document document, String output) {
int start = output.indexOf("<div id=\"toc\" class=\"toc\">");
if(start == -1) {
// no toc found, exit
return output;
}
String tocEndString = "</ul>\n</div>";
int end = output.indexOf(tocEndString, start);
if(end == -1) {
// bad, no end..
return output;
}
end += tocEndString.length() + 1;
org.jsoup.nodes.Document tocDoc = Jsoup.parseBodyFragment(output.substring(start, end));
tocDoc.select("ul").addClass("nav");
tocDoc.select("a").addClass("nav-link");
tocDoc.select("div#toc").addClass("toc-side");
String toc = tocDoc.body().html();
Object destDir = document.getOptions().get(Options.DESTINATION_DIR);
Object docname = ((Map)document.getOptions().get(Options.ATTRIBUTES)).get("docname");
Path path = FileSystems.getDefault().getPath((String) destDir, docname + ".toc.html");
StandardOpenOption[] options = {
StandardOpenOption.TRUNCATE_EXISTING,
StandardOpenOption.CREATE,
StandardOpenOption.WRITE
};
try(BufferedWriter br = Files.newBufferedWriter(path, options)) {
br.write(toc, 0, toc.length());
br.flush();
} catch (IOException ex) {
ex.printStackTrace(System.err);
}
if(start == 0) {
return output.substring(end);
}
return output.substring(0, start) + output.substring(end);
}