Created
September 8, 2015 16:16
-
-
Save struberg/01074b617e3f0e364228 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a simple Reader for java.nio.RandomAccessFile.
Sample usage is
This is needed as RandomAccessFile#readLine() reads byte-by-byte - how mad is that?