1 17 18 package org.apache.james.mailrepository.filepair; 19 20 import java.io.BufferedInputStream ; 21 import java.io.File ; 22 import java.io.FileInputStream ; 23 import java.io.IOException ; 24 import java.io.InputStream ; 25 26 28 public class ResettableFileInputStream 29 extends InputStream 30 { 31 protected static final int DEFAULT_BUFFER_SIZE = 1024; 32 33 protected final String m_filename; 34 protected int m_bufferSize; 35 protected InputStream m_inputStream; 36 protected long m_position; 37 protected long m_mark; 38 protected boolean m_isMarkSet; 39 40 public ResettableFileInputStream( final File file ) 41 throws IOException 42 { 43 this( file.getCanonicalPath() ); 44 } 45 46 public ResettableFileInputStream( final String filename ) 47 throws IOException 48 { 49 this( filename, DEFAULT_BUFFER_SIZE ); 50 } 51 52 public ResettableFileInputStream( final String filename, final int bufferSize ) 53 throws IOException 54 { 55 m_bufferSize = bufferSize; 56 m_filename = filename; 57 m_position = 0; 58 59 m_inputStream = newStream(); 60 } 61 62 public void mark( final int readLimit ) 63 { 64 m_isMarkSet = true; 65 m_mark = m_position; 66 m_inputStream.mark( readLimit ); 67 } 68 69 public boolean markSupported() 70 { 71 return true; 72 } 73 74 public void reset() 75 throws IOException 76 { 77 if( !m_isMarkSet ) 78 { 79 throw new IOException ( "Unmarked Stream" ); 80 } 81 try 82 { 83 m_inputStream.reset(); 84 } 85 catch( final IOException ioe ) 86 { 87 try 88 { 89 m_inputStream.close(); 90 m_inputStream = newStream(); 91 m_inputStream.skip( m_mark ); 92 m_position = m_mark; 93 } 94 catch( final Exception e ) 95 { 96 throw new IOException ( "Cannot reset current Stream: " + e.getMessage() ); 97 } 98 } 99 } 100 101 protected InputStream newStream() 102 throws IOException 103 { 104 return new BufferedInputStream ( new FileInputStream ( m_filename ), m_bufferSize ); 105 } 106 107 public int available() 108 throws IOException 109 { 110 return m_inputStream.available(); 111 } 112 113 public void close() throws IOException 114 { 115 m_inputStream.close(); 116 } 117 118 public int read() throws IOException 119 { 120 m_position++; 121 return m_inputStream.read(); 122 } 123 124 public int read( final byte[] bytes, final int offset, final int length ) 125 throws IOException 126 { 127 final int count = m_inputStream.read( bytes, offset, length ); 128 m_position += count; 129 return count; 130 } 131 132 public long skip( final long count ) 133 throws IOException 134 { 135 m_position += count; 136 return m_inputStream.skip( count ); 137 } 138 } 139 | Popular Tags |