当前位置: 代码迷 >> 综合 >> Java FileChannel
  详细解决方案

Java FileChannel

热度:28   发布时间:2023-12-18 09:53:31.0
  • FileChannel的优点
  • 1.在文件特定位置进行读写操作
    2.将文件一部分直接加载到内存,这样效率更高
    3.以更快的速度将文件数据从一个通道传输到另一个通道
    4.锁定文件的某一部分来限制其他线程访问
    5.为了避免数据丢失,强制立即将更新写入文件并存储

  • FileChannel读操作
  •   try (RandomAccessFile reader = new RandomAccessFile("./comm.txt", "r");FileChannel channel = reader.getChannel();ByteArrayOutputStream out = new ByteArrayOutputStream()) {int bufferSize = 1024;if (bufferSize > channel.size()) {bufferSize = (int) channel.size();}ByteBuffer buff = ByteBuffer.allocate(bufferSize);while (channel.read(buff) > 0) {out.write(buff.array(), 0, buff.position());buff.clear();}String fileContent = new String(out.toByteArray(), StandardCharsets.UTF_8);System.out.println(fileContent);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
    

    读方法中获得channel的方法:

    //RandomAccessFile获得
    RandomAccessFile reader = new RandomAccessFile(file, "r");
    FileChannel channel = reader.getChannel();//FileInputStream获得
    FileInputStream fin= new FileInputStream(file);
    FileChannel channel = fin.getChannel();
    
  • FileChannel写操作
  •   String file = "./test.txt";try (RandomAccessFile writer = new RandomAccessFile(file, "rw");FileChannel channel = writer.getChannel()) {ByteBuffer buff = ByteBuffer.wrap("Hello world".getBytes(StandardCharsets.UTF_8));channel.write(buff);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
    

    写方法中获得channel的方法:

    //RandomAccessFile获得
    RandomAccessFile writer = new RandomAccessFile(file, "rw");
    FileChannel channel = writer.getChannel();//FileOutputStream获得
    FileOutputStream fout = new FileOutputStream(file);
    //FileOutputStream fout = new FileOutputStream(file,true);接着文件尾部进行写入
    FileChannel channel = fout.getChannel();
    
  • 改变读/写位置
  • channel.position(n);
    
  • 获取文件大小
  • channel.size(n);
    
  • 截断文件
  • //方法将文件截断为给定的大小(以字节为单位)
    channel = channel.truncate(n);
    
  • 强制更新
  • channel.force(true);
    
  • 将文件部分加载到内存
  • try (RandomAccessFile reader = new RandomAccessFile("./test.txt", "r");FileChannel channel = reader.getChannel();ByteArrayOutputStream out = new ByteArrayOutputStream()) {MappedByteBuffer buff = channel.map(FileChannel.MapMode.READ_ONLY, 6, 5);if(buff.hasRemaining()) {byte[] data = new byte[buff.remaining()];buff.get(data);}
    } catch (FileNotFoundException e) {e.printStackTrace();
    } catch (IOException e) {e.printStackTrace();
    }
    

    类似地,可以使用FileChannel.MapMode.READ_WRITE以读写模式打开文件。还可以使用FileChannel.MapMode.PRIVATE模式,该模式下,更改不应用于原始文件。

  • 锁定文件部分
  • FileLock fileLock = channel.tryLock(long position, long size, booean  shared)
    
  相关解决方案