本文整理汇总了Java中java.nio.channels.FileChannel.close方法的典型用法代码示例。如果您正苦于以下问题:Java FileChannel.close方法的具体用法?Java FileChannel.close怎么用?Java FileChannel.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.nio.channels.FileChannel
的用法示例。
在下文中一共展示了FileChannel.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: extractDatabase
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
private static String extractDatabase(Context context) {
try {
File external = context.getExternalFilesDir(null);
File data = Environment.getDataDirectory();
if (external != null && external.canWrite()) {
String dataDBPath = "data/" + context.getPackageName() + "/databases/chuck.db";
String extractDBPath = "chuckdb.temp";
File dataDB = new File(data, dataDBPath);
File extractDB = new File(external, extractDBPath);
if (dataDB.exists()) {
FileChannel in = new FileInputStream(dataDB).getChannel();
FileChannel out = new FileOutputStream(extractDB).getChannel();
out.transferFrom(in, 0, in.size());
in.close();
out.close();
return extractDB.getAbsolutePath();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
示例2: corruptTranslogs
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
* Randomly overwrite some bytes in the translog files
*/
private void corruptTranslogs(Path directory) throws Exception {
Path[] files = FileSystemUtils.files(directory, "translog-*");
for (Path file : files) {
logger.info("--> corrupting {}...", file);
FileChannel f = FileChannel.open(file, StandardOpenOption.READ, StandardOpenOption.WRITE);
int corruptions = scaledRandomIntBetween(10, 50);
for (int i = 0; i < corruptions; i++) {
// note: with the current logic, this will sometimes be a no-op
long pos = randomIntBetween(0, (int) f.size());
ByteBuffer junk = ByteBuffer.wrap(new byte[]{randomByte()});
f.write(junk, pos);
}
f.close();
}
}
示例3: analyzeAndTagFile
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
private static void analyzeAndTagFile(String inputFilename) throws Exception {
File file = new File(inputFilename);
String outFilename = config.getString("output.dirpath") + file.getName() + config.getString("output.postfix");
RandomAccessFile outStream = new RandomAccessFile(outFilename, "rw");
FileChannel outChannel = outStream.getChannel();
LineIterator it = FileUtils.lineIterator(file, config.getString("input.charset"));
try {
while (it.hasNext()) {
String line = it.nextLine().trim();
if (!"".equals(line)) {
outChannel.write(Charset.forName(config.getString("output.charset")).newEncoder().encode(CharBuffer.wrap(tagger.tag(komoran.analyze(line)) + config.getString("delimiter.line"))));
}
}
}
finally {
LineIterator.closeQuietly(it);
outStream.close();
outChannel.close();
}
}
示例4: copyFile
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public static void copyFile(File src, File dest) throws IOException {
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
if (!dest.exists()) {
dest.createNewFile();
}
inChannel = (new FileInputStream(src)).getChannel();
outChannel = (new FileOutputStream(dest)).getChannel();
inChannel.transferTo(0L, inChannel.size(), outChannel);
} finally {
if (inChannel != null) {
inChannel.close();
}
if (outChannel != null) {
outChannel.close();
}
}
}
示例5: readBytes
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
* 将整个文件读取为字节数组
*
* @param path
* @return
*/
public static byte[] readBytes(String path) {
try {
FileInputStream fis = new FileInputStream(path);
FileChannel channel = fis.getChannel();
int fileSize = (int) channel.size();
ByteBuffer byteBuffer = ByteBuffer.allocate(fileSize);
channel.read(byteBuffer);
byteBuffer.flip();
byte[] bytes = byteBuffer.array();
byteBuffer.clear();
channel.close();
fis.close();
return bytes;
} catch (Exception e) {
logger.warn("读取" + path + "时发生异常" + e);
logger.warn("开始生成" + path + " ...");
}
return null;
}
示例6: copy
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
* 复制文件
*
* @param source
* @param target
* @throws IOException
*/
public void copy(File source, File target) throws IOException
{
// FileInputStream sourceStream = null;
// FileInputStream targetStream = null;
FileChannel inChannel = new FileInputStream(source).getChannel();
FileChannel outChannel = new FileOutputStream(target).getChannel();
try
{
inChannel.transferTo(0, inChannel.size(), outChannel);
}
catch (IOException e)
{
Log.E(TAG, "Failed to copy file. " + e.toString());
e.printStackTrace();
}
finally
{
if (inChannel != null)
{
inChannel.close();
}
if (outChannel != null)
{
outChannel.close();
}
// if (targetStream != null)
// {
// targetStream.close();
// }
// if (sourceStream != null)
// {
// sourceStream.close();
// }
}
}
示例7: testRandomAccessRead
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
* Tests random access reading
* <p>
* Only executes if the reader implements {@link RandomAccessContent}.
*/
@Test
public void testRandomAccessRead() throws Exception
{
ContentStore store = getStore();
String contentUrl = getExistingContentUrl();
if (contentUrl == null)
{
logger.warn("Store test testRandomAccessRead not possible on " + store.getClass().getName());
return;
}
// Get the reader
ContentReader reader = store.getReader(contentUrl);
assertNotNull("Reader should never be null", reader);
FileChannel fileChannel = reader.getFileChannel();
assertNotNull("No channel given", fileChannel);
// check that no other content access is allowed
try
{
reader.getReadableChannel();
fail("Second channel access allowed");
}
catch (RuntimeException e)
{
// expected
}
fileChannel.close();
}
示例8: shouldThrowLockExceptionIfFailedToLockStateDirectory
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Test
public void shouldThrowLockExceptionIfFailedToLockStateDirectory() throws Exception {
final File taskDirectory = stateDirectory.directoryForTask(taskId);
final FileChannel channel = FileChannel.open(new File(taskDirectory,
StateDirectory.LOCK_FILE_NAME).toPath(),
StandardOpenOption.CREATE,
StandardOpenOption.WRITE);
// lock the task directory
final FileLock lock = channel.lock();
try {
new ProcessorStateManager(
taskId,
noPartitions,
false,
stateDirectory,
Collections.<String, String>emptyMap(),
changelogReader,
false);
fail("Should have thrown LockException");
} catch (final LockException e) {
// pass
} finally {
lock.release();
channel.close();
}
}
示例9: copyFile
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public static void copyFile(File from, File to) throws IOException {
if (!from.exists()) {
throw new FileNotFoundException();
}
if (from.isDirectory() || to.isDirectory()) {
throw new FileNotFoundException();
}
FileInputStream fi = null;
FileChannel in = null;
FileOutputStream fo = null;
FileChannel out = null;
try {
if (!to.exists()) {
to.createNewFile();
}
fi = new FileInputStream(from);
in = fi.getChannel();
fo = new FileOutputStream(to);
out = fo.getChannel();
in.transferTo(0, in.size(), out);
} finally {
if (fi != null) fi.close();
if (in != null) in.close();
if (fo != null) fo.close();
if (out != null) out.close();
}
}
示例10: writeToFile
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
* Writes data to a file.
*
* @param data
* @throws IOException
*/
protected void writeToFile(List<ExportEntry> data) throws IOException {
FileChannel fc = fileOutpuStream.getChannel();
byte[] lineFeed = "\n".getBytes(Charset.forName("UTF-8"));
for (ExportEntry entry : data) {
byte[] messageBytes = entry.toByteEntryLine();
fc.write(ByteBuffer.wrap(messageBytes));
fc.write(ByteBuffer.wrap(lineFeed));
}
fc.close();
}
示例11: writeToFile
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
* {@inheritDoc}
*/
@Override
protected void writeToFile(final List<ExportEntry> data) throws IOException {
FileChannel channel = fileOutputStream.getChannel();
byte[] lineFeed = "\n".getBytes(Charset.forName("UTF-8"));
for (ExportEntry entry : data) {
byte[] messageBytes = entry.toByteEntryLine();
channel.write(ByteBuffer.wrap(messageBytes));
channel.write(ByteBuffer.wrap(lineFeed));
}
channel.close();
}
示例12: addLibrary
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public void addLibrary(String name) throws Exception {
OpenArch.log.info(String.format("Loading %s.", name));
String libPath = String.format("/assets/%s/lib/%s", OpenArch.MODID, name);
URL libUrl = getClass().getResource(libPath);
ReadableByteChannel in = Channels.newChannel(libUrl.openStream());
String tmpLibPath = String.format("%s/%s", tmpDir, name);
File tmpLibFile = new File(tmpLibPath);
if (tmpLibFile.exists()) {
return;
}
FileChannel out = new FileOutputStream(tmpLibFile).getChannel();
out.transferFrom(in, 0, Long.MAX_VALUE);
tmpLibFile.deleteOnExit();
if (!tmpLibFile.setReadable(true, false)) {
throw new Exception("Failed to set readable flag on the library");
}
if (!tmpLibFile.setWritable(true, false)) {
throw new Exception("Failed to set writable flag on the library");
}
if (!tmpLibFile.setExecutable(true, false)) {
throw new Exception("Failed to set executable flag on the library");
}
out.close();
in.close();
}
示例13: lockGlobalState
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
boolean lockGlobalState(final int retry) throws IOException {
if (globalStateLock != null) {
log.trace("{} Found cached state dir lock for the global task", logPrefix);
return true;
}
final File lockFile = new File(globalStateDir(), LOCK_FILE_NAME);
final FileChannel channel;
try {
channel = FileChannel.open(lockFile.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
} catch (NoSuchFileException e) {
// FileChannel.open(..) could throw NoSuchFileException when there is another thread
// concurrently deleting the parent directory (i.e. the directory of the taskId) of the lock
// file, in this case we will return immediately indicating locking failed.
return false;
}
final FileLock fileLock = tryLock(retry, channel);
if (fileLock == null) {
channel.close();
return false;
}
globalStateChannel = channel;
globalStateLock = fileLock;
log.debug("{} Acquired global state dir lock", logPrefix);
return true;
}
示例14: TrieDictionary
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
private TrieDictionary(File data) throws IOException {
this.array = null;
FileInputStream ins = new FileInputStream(data);
FileChannel channel = ins.getChannel();
try {
this.buffer = channel.map(MapMode.READ_ONLY, 0, channel.size());
} finally {
channel.close();
ins.close();
}
}
示例15: unLock
import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
* unlock odex file
**/
public void unLock(File targetFile) {
File lockFile = new File(targetFile.getParentFile().getAbsolutePath().concat("/lock"));
if (!lockFile.exists()) {
return;
}
if (this.mRefCountMap.containsKey(lockFile.getAbsolutePath())) {
FileLockCount fileLockCount = this.mRefCountMap.get(lockFile.getAbsolutePath());
if (fileLockCount != null) {
java.nio.channels.FileLock fileLock = fileLockCount.mFileLock;
RandomAccessFile randomAccessFile = fileLockCount.fOs;
FileChannel fileChannel = fileLockCount.fChannel;
try {
if (RefCntDec(lockFile.getAbsolutePath()) <= 0) {
if (fileLock != null && fileLock.isValid()) {
fileLock.release();
}
if (randomAccessFile != null) {
randomAccessFile.close();
}
if (fileChannel != null) {
fileChannel.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}