- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我目前正在开发一个应用程序,需要随机访问许多(60k-100k)相对较大的文件。由于打开和关闭流是一项相当昂贵的操作,因此我更愿意将最大文件的 FileChannel 保持打开状态,直到不再需要它们为止。
问题是,由于 Java 7 的 try-with 语句未涵盖这种行为,因此我需要手动关闭所有 FileChannel。但这变得越来越复杂,因为可以在整个软件中同时访问相同的文件。
我已经实现了一个 ChannelPool 类,它可以跟踪每个注册路径打开的 FileChannel 实例。然后可以发出 ChannelPool 来关闭那些其 Path 仅在一定时间间隔内被池本身弱引用的 channel 。我更喜欢事件监听器方法,但我也不想监听 GC。
FileChannelPool来自 Apache Commons 的方法并不能解决我的问题,因为 channel 仍然需要手动关闭。
这个问题有更优雅的解决方案吗?如果没有,我的实现如何改进?
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
public class ChannelPool {
private static final ChannelPool defaultInstance = new ChannelPool();
private final ConcurrentHashMap<String, ChannelRef> channels;
private final Timer timer;
private ChannelPool(){
channels = new ConcurrentHashMap<>();
timer = new Timer();
}
public static ChannelPool getDefault(){
return defaultInstance;
}
public void initCleanUp(){
// wait 2 seconds then repeat clean-up every 10 seconds.
timer.schedule(new CleanUpTask(this), 2000, 10000);
}
public void shutDown(){
// must be called manually.
timer.cancel();
closeAll();
}
public FileChannel getChannel(Path path){
ChannelRef cref = channels.get(path.toString());
System.out.println("getChannel called " + channels.size());
if (cref == null){
cref = ChannelRef.newInstance(path);
if (cref == null){
// failed to open channel
return null;
}
ChannelRef oldRef = channels.putIfAbsent(path.toString(), cref);
if (oldRef != null){
try{
// close new channel and let GC dispose of it
cref.channel().close();
System.out.println("redundant channel closed");
}
catch (IOException ex) {}
cref = oldRef;
}
}
return cref.channel();
}
private void remove(String str) {
ChannelRef ref = channels.remove(str);
if (ref != null){
try {
ref.channel().close();
System.out.println("old channel closed");
}
catch (IOException ex) {}
}
}
private void closeAll() {
for (Map.Entry<String, ChannelRef> e : channels.entrySet()){
remove(e.getKey());
}
}
private void maintain() {
// close channels for derefenced paths
for (Map.Entry<String, ChannelRef> e : channels.entrySet()){
ChannelRef ref = e.getValue();
if (ref != null){
Path p = ref.pathRef().get();
if (p == null){
// gc'd
remove(e.getKey());
}
}
}
}
private static class ChannelRef{
private FileChannel channel;
private WeakReference<Path> ref;
private ChannelRef(FileChannel channel, WeakReference<Path> ref) {
this.channel = channel;
this.ref = ref;
}
private static ChannelRef newInstance(Path path) {
FileChannel fc;
try {
fc = FileChannel.open(path, StandardOpenOption.READ);
}
catch (IOException ex) {
return null;
}
return new ChannelRef(fc, new WeakReference<>(path));
}
private FileChannel channel() {
return channel;
}
private WeakReference<Path> pathRef() {
return ref;
}
}
private static class CleanUpTask extends TimerTask {
private ChannelPool pool;
private CleanUpTask(ChannelPool pool){
super();
this.pool = pool;
}
@Override
public void run() {
pool.maintain();
pool.printState();
}
}
private void printState(){
System.out.println("Clean up performed. " + channels.size() + " channels remain. -- " + System.currentTimeMillis());
for (Map.Entry<String, ChannelRef> e : channels.entrySet()){
ChannelRef cref = e.getValue();
String out = "open: " + cref.channel().isOpen() + " - " + cref.channel().toString();
System.out.println(out);
}
}
}
编辑:感谢fge的答案我现在已经得到了我所需要的。谢谢!
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.ExecutionException;
public class Channels {
private static final LoadingCache<Path, FileChannel> channelCache =
CacheBuilder.newBuilder()
.weakKeys()
.removalListener(
new RemovalListener<Path, FileChannel>(){
@Override
public void onRemoval(RemovalNotification<Path, FileChannel> removal) {
FileChannel fc = removal.getValue();
try {
fc.close();
}
catch (IOException ex) {}
}
}
)
.build(
new CacheLoader<Path, FileChannel>() {
@Override
public FileChannel load(Path path) throws IOException {
return FileChannel.open(path, StandardOpenOption.READ);
}
}
);
public static FileChannel get(Path path){
try {
return channelCache.get(path);
}
catch (ExecutionException ex){}
return null;
}
}
最佳答案
看这里:
http://code.google.com/p/guava-libraries/wiki/CachesExplained
您可以将 LoadingCache
与删除监听器一起使用,该监听器会在 channel 过期时为您关闭 channel ,并且您可以在访问或写入后指定过期时间。
关于java - 有没有办法让 FileChannel 自动关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14186462/
我正在考虑更改 this question进入我的情况。然后我决定我的情况需要自己的问题并希望得到答案。在调用 FileChannel.truncate() 减小文件大小后,我调用 FileChann
我已阅读关于 FileChannel 的 transferFrom 的评论 * This method is potentially much more efficient than a simp
我必须按照小端顺序写一个整数。所以我创建了一个带有 FileChannel 属性和一些写入方法的类(此类不扩展任何内容)。 但是有一个问题:只有一种方法有效,另一种无效! 这里是工作方法(dis是Fi
以下是我将一个文件附加到另一个文件的方法。 public static void appendFile(File baseFile, File newFile) throws IOException
我正在创建一个 fileChannel 来执行内存映射写入。该文件 channel 的大小为 100 字节。我只向其中写入 80 个字节。因此,当我稍后读取该文件时,它会在 and 上添加 5 个“0
我有一个 IO 类,它使用 ByteBuffer 来缓冲对 FileChannel 的访问(因此它基本上在构造函数中接受 FileChannel)。我想对它进行单元测试,所以如果我能得到一个字节数组支
我是 Java NIO 新手。我发现 FileChannel 对象具有读取和写入方法。但我无法在单个时间点使用相同的 FileChannel 进行读写。有没有办法做到这一点? 最佳答案 从具有“rw”
使用 FileChannel.position() 从不同线程写入一个文件是否安全?这对于分段下载是必需的。每个线程都会写入其在文件中的位置,即线程的位置不会相交。 最佳答案 虽然单个选项是线程安全的
在读取大文件时,我从这段代码中得到了一些奇怪的输出,该文件是使用 while 循环打印到 99,999 位数的,但是,在读取文件并打印内容时,它只输出 99,988 行。另外,使用 ByteBuffe
我正在使用fileChannel.lock(long position, long size, boolean shared)获得文件特定部分的独占访问权限。具体代码为: fileChannel.lo
我尝试使用 FileChannel 将特定字节写入文件的特定位置。但实际上文件缩小到我写更改的最后位置。我这样做: Path path = Paths.get("I://music - Cop
我正在使用 FileChannel 将 2MB 数据写入文件。 private void write(int numEntries, int entrySize) throws Exc
我有一个管道,我需要从中读取数据。但是,正如我在阅读之前所了解的那样,我必须创建一定大小的缓冲区。问题是如何定义缓冲区的大小以从管道读取所有数据? 这是我的代码: RandomAccessFile a
我正在尝试使用以下方法连接一组文本文件。但是,只有第一个文件显示在输出文件中。 public void concatenateFiles(List fileLocations, String outp
当我执行以下类(class)时 import java.io.*; import java.nio.*; import java.nio.file.*; import java.nio.channel
我目前正在开发一个应用程序,需要随机访问许多(60k-100k)相对较大的文件。由于打开和关闭流是一项相当昂贵的操作,因此我更愿意将最大文件的 FileChannel 保持打开状态,直到不再需要它们为
我正在使用 RandomAccessFile 打开大文件(~ 200 MB),然后获取它的 Channel。我正在尝试将一些数据映射到 MappedByteBuffer,但出现异常: Channel
文件 a.txt 看起来像: ABC 文件 d.txt 看起来像: DEF 我正在尝试获取“DEF”并将其附加到“ABC”,因此 a.txt 看起来像 ABC DEF 我尝试过的方法总是完全覆盖第一个
对于我的特定任务,我需要从 FileChannel 中读取数据到 Stream (或 Collection )属于 String的。 在常规 NIO对于 Path我们可以使用一个方便的方法Files.
我想我误解了 FileChannel 的锁定功能是如何工作的。 我想在一个文件上拥有独占写入锁,但允许从任何进程读取。 在运行 Java 7 的 Windows 7 机器上,我可以使用 FileCha
我是一名优秀的程序员,十分优秀!