import java.io.*;
import java.nio.file.*;

public class RandomAccessFileTest {
	public static void main(final String[] args) throws Exception {
		System.out.println("running test against Java version " + System.getProperty("java.version") + " (" + System.getProperty("java.vm.version") + ")");

		// create a temp file with some content
		final Path p = Files.createTempFile("test-", ".txt");
		Files.writeString(p, "hello\n");

		// create a RandomAccessFile
		final RandomAccessFile raf = new Buffered(p);
		
		// read the line from the file
		final String line = raf.readLine();
		if (line == null) {
			throw new RuntimeException("RandomeAccessFile.readLine() returned null for first line of file " + p);
		}
		if (!line.equals("hello")) {
			throw new RuntimeException("unexpected line read from RandomAccessFile.readLine(): \"" + line + "\"");
		}
		System.out.println("Read first line=\"" + line + "\" from file " + p);
	}

	private static final class Buffered extends RandomAccessFile {
		private final Path p;
		private final byte[] fileContent;
		private int currentOffset = 0;

		private Buffered(final Path p) throws IOException {
			super(p.toFile(), "r");
			this.p = p;
			this.fileContent = eagerlyReadUsingSuper();
		}

		private byte[] eagerlyReadUsingSuper() throws IOException {
			int n = -1;
			final byte[] buf = new byte[1024];
			final ByteArrayOutputStream baos = new ByteArrayOutputStream();

			while ((n = super.read(buf)) != -1) {
				baos.write(buf, 0, n);
			}
			
			return baos.toByteArray();
		}

		@Override
		public int read() throws IOException {
			if (currentOffset == fileContent.length) {
				return -1;
			}
			return fileContent[currentOffset++];
		}
	}
}