Java文件读取前中后200字节

Java文件读取前中后200字节

Posted by wenfengSAT on March 15, 2018

Java文件读取前中后200字节

Java文件读取前40+10字节,分两次读,一次读20字节


public static void main(String[] args) throws Exception {
		//String hex = "0x0000000003F985B8";
		/*String hex = "0x0000000003F9A790";
		Long x = Long.parseLong(hex.substring(2),16);//从第2个字符开始截取
		System.out.println(x);*/
		
		
		//读取文件时缓冲区大小
		//int BUFFER_SIZE = 1 * 1024 * 1024; 
		int BUFFER_SIZE = 20;
		FileInputStream fis = new FileInputStream("E://扫描//2018-3-12//xwsun//addr.txt");
		InputStream in = new BufferedInputStream(fis,BUFFER_SIZE);
		byte[] buffer = new byte[BUFFER_SIZE];
		byte[] lastByte = new byte[10];
		long count = 0;
		//int byteNum  = 20;
		//in.skip(byteNum);		//跳过前byteNum的字节不扫描
		int postion = in.read(buffer);
		int perReadByte = postion;
        while (perReadByte != -1)
        {
        	byte[] tempBuffer = null;
        	if(count >0)
        	{
        		tempBuffer = new byte[buffer.length + lastByte.length];
        		for(int i =0;i<lastByte.length;i++)
        		{
        			tempBuffer[i] = lastByte[i];
        		}
        		for(int i =0;i<buffer.length;i++)
        		{
        			tempBuffer[i + lastByte.length] = buffer[i];
        		}
        	}else{
        		tempBuffer = buffer;
        	}
        	
        	//输出一次读出的内容(一次读出20字节)
        	System.out.println(new String(tempBuffer,"UTF-8")+"==========================");
        	
        	
	    	int available = in.available();
	    	//最后300个字节
	    	lastByte = new byte[available > 10 ? 10 : available];
	    	
	    	for(int i=buffer.length - lastByte.length,j=0;i<buffer.length;i++,j++)
    		{
    			lastByte[j] = buffer[i];
    		}
            buffer = new byte[BUFFER_SIZE];
            count ++ ;
            if(count == 2)
            {
            	break;
            }
            perReadByte = in.read(buffer);
        }
	}

Java文件读取前40+10字节,分两次读,一次读20字节