1 /*******************************************************************************
2  *  Copyright (c) 2005, 2014 IBM Corporation and others.
3  *
4  *  This program and the accompanying materials
5  *  are made available under the terms of the Eclipse Public License 2.0
6  *  which accompanies this distribution, and is available at
7  *  https://www.eclipse.org/legal/epl-2.0/
8  *
9  *  SPDX-License-Identifier: EPL-2.0
10  *
11  *  Contributors:
12  *     IBM Corporation - initial API and implementation
13  *******************************************************************************/
14 package org.eclipse.ui.internal.views.log;
15 
16 import java.io.*;
17 
18 public class TailInputStream extends InputStream {
19 
20 	private RandomAccessFile fRaf;
21 
22 	private long fTail;
23 
TailInputStream(File file, long maxLength)24 	public TailInputStream(File file, long maxLength) throws IOException {
25 		super();
26 		fTail = maxLength;
27 		fRaf = new RandomAccessFile(file, "r"); //$NON-NLS-1$
28 		skipHead(file);
29 	}
30 
skipHead(File file)31 	private void skipHead(File file) throws IOException {
32 		if (file.length() > fTail) {
33 			fRaf.seek(file.length() - fTail);
34 			// skip bytes until a new line to be sure we start from a beginning of valid UTF-8 character
35 			int c = read();
36 			while (c != '\n' && c != '\r' && c != -1) {
37 				c = read();
38 			}
39 
40 		}
41 	}
42 
43 	@Override
read()44 	public int read() throws IOException {
45 		byte[] b = new byte[1];
46 		int len = fRaf.read(b, 0, 1);
47 		if (len < 0) {
48 			return len;
49 		}
50 		return b[0];
51 	}
52 
53 	@Override
read(byte[] b)54 	public int read(byte[] b) throws IOException {
55 		return fRaf.read(b, 0, b.length);
56 	}
57 
58 	@Override
read(byte[] b, int off, int len)59 	public int read(byte[] b, int off, int len) throws IOException {
60 		return fRaf.read(b, off, len);
61 	}
62 
63 	@Override
close()64 	public void close() throws IOException {
65 		fRaf.close();
66 	}
67 
68 }
69