⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 buffermanager.java

📁 用JAVA实现的miniSQL
💻 JAVA
字号:
import java.io.*;
import java.util.*;

public class BufferManager {
    LinkedList<Block> list;
    public BufferManager() {
    	list = new LinkedList<Block>();
    }
    public int getBlock(File file, long page, long head){
     	try{
     	int inbuffer=this.isInBuffer(file,page);
     	if(inbuffer!=-1){
     	     Block temp=list.get(inbuffer);
     	     list.remove(inbuffer);
     	     list.addFirst(temp);
     	}
     	else{
     	long blockaddress = head + page*4096;
    	RandomAccessFile accessfile = new RandomAccessFile(file, "r");
    	accessfile.seek(blockaddress);
    	byte[] context = new byte[4096];
    	try{
    		accessfile.readFully(context, 0, 4096);
        }catch(EOFException e){
    		System.out.println("文件已经结尾");
    		return -1;
    	}
    	Block block = new Block(file.toString(),page, head,context);
    	list.addFirst(block);
    	if(list.size()>100)
    	{
    		for(int i=0; i<list.size()-100;i++){
    		    Block tempchange = list.get(100+i);
    		    this.resetFile(i+100,new File(tempchange.filename),tempchange.blockno, tempchange.head);
    		}
    		int j=list.size();
    		for(int i=0; i<j-100 ; i++){
    			list.removeLast();
    		}	
    	}
        accessfile.close();
        }
     	}catch(Exception e){
     		return -1;
     	}
        return 1;
        
    }
    public void deleteBlock(String table){
    	for(int i=0; i<list.size();i++){
    		if(list.get(i).filename.equals(table)){
    			list.remove(i);
    			i--;
    		}
    	}
    }
    public void resetFile(int i,File file, long page, long head)
    {
    	try{
    	long blockaddress = head + page*4096;
    	RandomAccessFile accessfile = new RandomAccessFile(file, "rw");
    	accessfile.seek(blockaddress);
    	Block context = (Block)list.get(i);
    	accessfile.write(context.getByte(),0,4096);
    	accessfile.close();
    	}catch(Exception e){
    	}
    }
    public int isInBuffer(File file, long page) throws Exception{
    	Block temp;
    	for(int i=0; i<list.size(); i++)
    		if((temp=list.get(i)).filename.equals(file.toString())&&temp.blockno==page )
    			return i;
    	return -1;
    }
    public void quit(){
    	for(int i=0; i<list.size();i++){
    	    Block tempchange = list.get(i);
    	    this.resetFile(i,new File(tempchange.filename),tempchange.blockno, tempchange.head);
    	}
    	int j=list.size();
    	for(int i=0; i<j ; i++){
    		list.removeFirst();
    	}
    	System.out.print("quit successfully");
    	System.exit(0);
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -