Skip to content

Instantly share code, notes, and snippets.

@loganmzz
Created January 24, 2018 16:31
Show Gist options
  • Save loganmzz/14d1e5740f7e7d9d1dc936c88e86e04e to your computer and use it in GitHub Desktop.
Save loganmzz/14d1e5740f7e7d9d1dc936c88e86e04e to your computer and use it in GitHub Desktop.
Java Random Reader
package org.apache.jmeter.services;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;
import java.util.concurrent.ThreadLocalRandom;
public class RandomReader implements Closeable {
class Buffer {
private byte[] content = new byte[0];
private int length = 0;
private int mark = 0;
int length() {
return this.length;
}
Buffer append(byte[] bytes, int offset, int length) {
if ( (this.length + length ) > this.content.length) {
// Reallocate
byte[] temp = this.content;
this.content = new byte[this.content.length + Math.max(BUFFER_SIZE, length)];
System.arraycopy(temp, 0, this.content, 0, this.length);
}
System.arraycopy(bytes, 0, this.content, this.length, length);
return this;
}
boolean lookup(byte[] sequence) {
int newmark = this.mark;
for (byte[] eol : eols) {
int lastmatch = -1;
for (int i = this.mark; i < this.length; i++) {
}
}
return false;
}
}
private static final int BUFFER_SIZE = 8*1024;
private static final String[] EOLS = { "\r\n", "\n", "\r" };
private RandomAccessFile stream;
private Charset charset;
private byte[][] eols;
public RandomReader(String filename, Charset charset) throws FileNotFoundException {
init(new RandomAccessFile(filename, "r"), charset);
}
public RandomReader(File file, Charset charset) throws FileNotFoundException {
init(new RandomAccessFile(file, "r"), charset);
}
private void init(RandomAccessFile stream, Charset charset) {
this.stream = stream;
this.charset = charset;
eols = new byte[EOLS.length][];
for (int i = 0; i < EOLS.length; i++) {
eols[i] = EOLS[i].getBytes(this.charset);
}
}
@Override
public void close() throws IOException {
this.stream.close();
}
protected long random() {
return ThreadLocalRandom.current().nextLong();
}
public String readLine() throws IOException {
ByteArrayOutputStream line = new ByteArrayOutputStream(BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int read;
while ( (read = this.stream.read(buffer, 0, BUFFER_SIZE)) >= 0) {
// Look-up EOL
for (int i = 0; i < ())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment