Skip to content

Instantly share code, notes, and snippets.

@struberg
Created September 8, 2015 16:16
Show Gist options
  • Save struberg/01074b617e3f0e364228 to your computer and use it in GitHub Desktop.
Save struberg/01074b617e3f0e364228 to your computer and use it in GitHub Desktop.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apacheextras.simplearchive.impl;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
/**
* Reader implementation which uses RandomAccessFile under the hood.
* Attention, no concurrent usage is allowed!
*
* @author <a href="mailto:struberg@yahoo.de">Mark Struberg</a>
*/
public class RandomAccessFileReader extends Reader{
private RandomAccessFile file;
public RandomAccessFileReader(RandomAccessFile randomAccessFile) {
this.file = randomAccessFile;
try {
file.seek(0);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
byte[] bBuf = new byte[len - off];
int bytesRead = file.read(bBuf);
if (bytesRead <= 0) {
return -1;
}
String s = new String(bBuf, StandardCharsets.UTF_8);
char[] cRead = s.toCharArray();
int i = 0;
while (i < len) {
if (i == cRead.length || cRead[i] == '\u0000') {
break;
}
cbuf[off + i] = cRead[i];
// continue with the next char
i++;
}
return i;
}
@Override
public void close() throws IOException {
file.close();
}
}
@struberg
Copy link
Author

struberg commented Sep 8, 2015

This is a simple Reader for java.nio.RandomAccessFile.

Sample usage is

        BufferedReader br = new BufferedReader(new RandomAccessFileReader(file), BUFFER_SIZE);
        String line = br.readLine();

This is needed as RandomAccessFile#readLine() reads byte-by-byte - how mad is that?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment