Java Code Examples for java.io.RandomAccessFile#read()

The following examples show how to use java.io.RandomAccessFile#read() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BinaryFunctions.java    From commons-imaging with Apache License 2.0 6 votes vote down vote up
public static byte[] getRAFBytes(final RandomAccessFile raf, final long pos,
        final int length, final String exception) throws IOException {
    final byte[] result = new byte[length];

    raf.seek(pos);

    int read = 0;
    while (read < length) {
        final int count = raf.read(result, read, length - read);
        if (count < 0) {
            throw new IOException(exception);
        }

        read += count;
    }

    return result;

}
 
Example 2
Source File: HeaderReader.java    From zip4j with Apache License 2.0 6 votes vote down vote up
private long determineOffsetOfEndOfCentralDirectory(RandomAccessFile randomAccessFile) throws IOException {
  byte[] buff = new byte[BUFF_SIZE];
  long currentFilePointer = randomAccessFile.getFilePointer();

  do {
    int toRead = currentFilePointer > BUFF_SIZE ? BUFF_SIZE : (int) currentFilePointer;
    // read 4 bytes again to make sure that the header is not spilled over
    long seekPosition = currentFilePointer - toRead + 4;
    if (seekPosition == 4) {
      seekPosition = 0;
    }

    seekInCurrentPart(randomAccessFile, seekPosition);
    randomAccessFile.read(buff, 0, toRead);
    currentFilePointer = seekPosition;

    for (int i = 0; i < toRead - 3; i++) {
      if (rawIO.readIntLittleEndian(buff, i) == HeaderSignature.END_OF_CENTRAL_DIRECTORY.getValue()) {
        return currentFilePointer + i;
      }
    }
  } while (currentFilePointer > 0);

  throw new ZipException("Zip headers not found. Probably not a zip file");
}
 
Example 3
Source File: FileUtil.java    From document-management-software with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Copy the given byte range of the given input to the given output.
 * 
 * @param input The input to copy the given range to the given output for.
 * @param output The output to copy the given range from the given input
 *        for.
 * @param start Start of the byte range.
 * @param length Length of the byte range.
 * @throws IOException If something fails at I/O level.
 */
private static void copy(RandomAccessFile input, OutputStream output, long start, long length) throws IOException {
	byte[] buffer = new byte[BUFF_SIZE];
	int read;

	if (input.length() == length) {
		// Write full range.
		while ((read = input.read(buffer)) > 0) {
			output.write(buffer, 0, read);
		}
	} else {
		// Write partial range.
		input.seek(start);
		long toRead = length;

		while ((read = input.read(buffer)) > 0) {
			if ((toRead -= read) > 0) {
				output.write(buffer, 0, read);
			} else {
				output.write(buffer, 0, (int) toRead + read);
				break;
			}
		}
	}
}
 
Example 4
Source File: SinParser.java    From Flashtool with GNU General Public License v3.0 6 votes vote down vote up
public String getDataTypePriv() throws IOException {
	RandomAccessFile fin = new RandomAccessFile(sinfile,"r");
	byte[] res=null;
	fin.seek(headerLen);
	if (hashLen==0) {
		res = new byte[(int)size-headerLen];
		fin.read(res);
	}
	else {
		int i=0;
		while (i < blocks.block.length && blocks.block[i].offset==0 ) {
			res = new byte[blocks.block[i].length];
			fin.read(res);
			i++;
		}
	}
	fin.close();
	return getDataTypePriv(res);
}
 
Example 5
Source File: ArchivePerformanceTest.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
void doFileRead( ) throws IOException
{
	for ( int i = 0; i < STREAM_COUNT; i++ )
	{
		RandomAccessFile file = new RandomAccessFile( "./utest/file/" + i,
				"rw" );
		byte[] buffer = new byte[BUFFER_SIZE];
		long offset = 0;
		do
		{
			int size = (int) Math.round( Math.random( ) * BUFFER_SIZE );
			if ( offset + size > STREAM_SIZE )
			{
				size = (int) ( STREAM_SIZE - offset );
			}
			file.seek( offset );
			offset += file.read( buffer, 0, size );
		} while ( offset < STREAM_SIZE );
		readSize += offset;
		file.close( );
	}
}
 
Example 6
Source File: ID3v2_2.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
public boolean seek(final RandomAccessFile file) throws IOException {
    final byte[] buffer = new byte[3];
    file.seek(0);

    // read the tag if it exists
    file.read(buffer, 0, 3);
    final String tag = new String(buffer, 0, 3);
    if (tag.equals("ID3") == false) {
        return false;
    }

    // read the major and minor @version number
    file.read(buffer, 0, 2);

    // read back the @version bytes so we can read and save them later
    file.seek(file.getFilePointer() - 2);
    return ((buffer[0] == 2) && (buffer[1] == 0));
}
 
Example 7
Source File: EncryptedFileDataSource.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
@Override
public long open(DataSpec dataSpec) throws EncryptedFileDataSourceException {
    try {
        uri = dataSpec.uri;
        File path = new File(dataSpec.uri.getPath());
        String name = path.getName();
        File keyPath = new File(FileLoader.getInternalCacheDir(), name + ".key");
        RandomAccessFile keyFile = new RandomAccessFile(keyPath, "r");
        keyFile.read(key);
        keyFile.read(iv);
        keyFile.close();

        file = new RandomAccessFile(path, "r");
        file.seek(dataSpec.position);
        fileOffset = (int) dataSpec.position;
        bytesRemaining = dataSpec.length == C.LENGTH_UNSET ? file.length() - dataSpec.position : dataSpec.length;
        if (bytesRemaining < 0) {
            throw new EOFException();
        }
    } catch (IOException e) {
        throw new EncryptedFileDataSourceException(e);
    }

    opened = true;
    transferStarted(dataSpec);

    return bytesRemaining;
}
 
Example 8
Source File: SinParser.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
public byte[] getHeader()  throws IOException {
	RandomAccessFile fin = new RandomAccessFile(sinfile,"r");
	byte[] buff = new byte[headerLen];
	fin.read(buff);
	fin.close();
	return buff;
}
 
Example 9
Source File: EncryptedFileInputStream.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
public EncryptedFileInputStream(File file, File keyFile) throws Exception {
    super(file);

    currentMode = MODE_CTR;
    RandomAccessFile randomAccessFile = new RandomAccessFile(keyFile, "r");
    randomAccessFile.read(key, 0, 32);
    randomAccessFile.read(iv, 0, 16);
    randomAccessFile.close();
}
 
Example 10
Source File: EncryptedFileInputStream.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
public static void decryptBytesWithKeyFile(byte[] bytes, int offset, int length, File keyFile) throws Exception {
    byte[] key = new byte[32];
    byte[] iv = new byte[16];
    RandomAccessFile randomAccessFile = new RandomAccessFile(keyFile, "r");
    randomAccessFile.read(key, 0, 32);
    randomAccessFile.read(iv, 0, 16);
    randomAccessFile.close();
    Utilities.aesCtrDecryptionByteArray(bytes, key, iv, offset, length, 0);
}
 
Example 11
Source File: AbstractLyrics3v2FieldBody.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
protected int readHeader(final RandomAccessFile file) throws InvalidTagException, IOException {
    final int size;
    final byte[] buffer = new byte[5];

    // read the 5 character size
    file.read(buffer, 0, 5);
    size = Integer.parseInt(new String(buffer, 0, 5));
    if ((size == 0) && (TagOptionSingleton.getInstance().isLyrics3KeepEmptyFieldIfRead() == false)) {
        throw new InvalidTagException("Lyircs3v2 Field has size of zero.");
    }
    return size;
}
 
Example 12
Source File: FaceRecognition.java    From albert with MIT License 5 votes vote down vote up
public void PGMReader(String filename) {
    File file = new File(filename);
    try {
        RandomAccessFile in = new RandomAccessFile(file, "r");
        in.read(imageinfor);
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    for (int i = 0; i < picSize; i++) {
        int temp = (int) imageinfor[i + 13];
        input[i] = (double) (temp + 128) / 255;
    }
    input[picSize] = 1.0;
}
 
Example 13
Source File: ReplayGainTagExtractor.java    From VinylMusicPlayer with GNU General Public License v3.0 5 votes vote down vote up
private static Map<String, Float> parseLameHeader(String path) throws IOException {
  // Method taken from adrian-bl/bastp library
  Map<String, Float> tags = new HashMap<>();
  RandomAccessFile s = new RandomAccessFile(path, "r");
  byte[] chunk = new byte[12];

  s.seek(0x24);
  s.read(chunk);

  String lameMark = new String(chunk, 0, 4, "ISO-8859-1");

  if (lameMark.equals("Info") || lameMark.equals("Xing")) {
    s.seek(0xAB);
    s.read(chunk);

    int raw = b2be32(chunk);
    int gtrk_raw = raw >> 16;     /* first 16 bits are the raw track gain value */
    int galb_raw = raw & 0xFFFF;  /* the rest is for the album gain value       */

    float gtrk_val = (float) (gtrk_raw & 0x01FF) / 10;
    float galb_val = (float) (galb_raw & 0x01FF) / 10;

    gtrk_val = ((gtrk_raw & 0x0200) != 0 ? -1 * gtrk_val : gtrk_val);
    galb_val = ((galb_raw & 0x0200) != 0 ? -1 * galb_val : galb_val);

    if ((gtrk_raw & 0xE000) == 0x2000) {
      tags.put(REPLAYGAIN_TRACK_GAIN, gtrk_val);
    }
    if ((gtrk_raw & 0xE000) == 0x4000) {
      tags.put(REPLAYGAIN_ALBUM_GAIN, galb_val);
    }
  }

  return tags;
}
 
Example 14
Source File: FieldBodyUnsupported.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public void read(final RandomAccessFile file) throws IOException {
    final int size;
    final byte[] buffer = new byte[5];

    // read the 5 character size
    file.read(buffer, 0, 5);
    size = Integer.parseInt(new String(buffer, 0, 5));
    this.value = new byte[size];

    // read the SIZE length description
    file.read(this.value);
}
 
Example 15
Source File: TailFile.java    From BigDataScript with Apache License 2.0 4 votes vote down vote up
/**
 * This is the typical 'tail' command behavior: Show the last 'n' lines of a file
 *
 * References: http://stackoverflow.com/questions/6888001/java-code-for-tail-n-lines-of-file-equivalent-to-tail-commad-in-unix
 *
 * @param fileName
 * @param numLines : Number of line to read. Negative means "ALL lines"
 * @return
 */
public static String tail(String fileName, int linesToRead) {
	if (linesToRead == 0) return "";

	// Read the whole file?
	if (linesToRead < 0) return Gpr.readFile(fileName);

	if (fileName == null) return null;
	File file = new File(fileName);
	if (file == null || !file.exists()) return null;
	if (file.length() <= 0) return "";

	// Read file
	final int chunkSize = 1024 * 64;
	List<String> lines = new ArrayList<>();
	StringBuilder latestLine = null;
	try {
		RandomAccessFile raf = new RandomAccessFile(file, "r");

		long end = raf.length();
		boolean readMore = true;
		while (readMore) {
			byte[] buf = new byte[chunkSize];

			// Read a chunk from the end of the file
			long startPoint = end - chunkSize;
			long readLen = chunkSize;
			if (startPoint < 0) {
				readLen = chunkSize + startPoint;
				startPoint = 0;
			}

			// Read
			raf.seek(startPoint);
			readLen = raf.read(buf, 0, (int) readLen);
			if (readLen <= 0) break;

			// Parse newlines and add them to an array
			int unparsedSize = (int) readLen;
			int indexMax = unparsedSize - 1;
			int index = indexMax;
			while (index >= 0) {
				if (isNewLine(buf, index, indexMax)) {
					int startOfLine = index + 1;
					int len = (unparsedSize - startOfLine);
					if (len >= 0) {
						lines.add(new String(buf, startOfLine, len) + (latestLine != null ? latestLine.toString() : ""));
						latestLine = null;
					}
					unparsedSize = index + 1;
				}
				--index;
			}

			if (unparsedSize > 0) {
				if (latestLine == null) latestLine = new StringBuilder();
				latestLine.insert(0, new String(buf, 0, unparsedSize));
			}

			// Move end point back by the number of lines we parsed
			// Note: We have not parsed the first line in the chunked
			// content because could be a partial line
			end = end - chunkSize;

			readMore = (lines.size() <= linesToRead) && (startPoint != 0);
		}

		raf.close();
	} catch (Exception e) {
		throw new RuntimeException("Error tail on file '" + fileName + "'", e);
	}

	// Add 'latest' line
	if (latestLine != null) lines.add(latestLine.toString());

	// Only return the requested number of lines
	StringBuilder sb = new StringBuilder();
	int max = Math.min(linesToRead, lines.size() - 1);
	for (int i = max; i >= 0; i--)
		sb.append(lines.get(i));

	return sb.toString();
}
 
Example 16
Source File: GrADSDataInfo.java    From MeteoInfo with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public GridData getGridData_Lon(int timeIdx, int latIdx, String varName, int levelIdx) {
    try {
        int varIdx = this.getVariableIndex(varName);
        String filePath = DSET;
        int tIdx = timeIdx;
        if (OPTIONS.template) {
            Object[] result = getFilePath_Template(timeIdx);
            filePath = (String) result[0];
            tIdx = (int) result[1];
        }
        RandomAccessFile br = new RandomAccessFile(filePath, "r");
        int i, lNum;
        byte[] aBytes = new byte[4];
        float aValue;

        GridData aGridData = new GridData();
        aGridData.missingValue = this.getMissingValue();
        aGridData.xArray = X;
        aGridData.yArray = new double[1];
        aGridData.yArray[0] = 0;
        aGridData.data = new double[1][X.length];

        br.seek(FILEHEADER + tIdx * RecLenPerTime);
        for (i = 0; i < varIdx; i++) {
            lNum = VARDEF.getVars().get(i).getLevelNum();
            if (lNum == 0) {
                lNum = 1;
            }
            br.seek(br.getFilePointer() + lNum * RecordLen);
        }
        br.seek(br.getFilePointer() + levelIdx * RecordLen);
        if (OPTIONS.sequential) {
            br.seek(br.getFilePointer() + 4);
        }
        br.seek(br.getFilePointer() + latIdx * XNum * 4);

        for (i = 0; i < XNum; i++) {
            br.read(aBytes);
            aValue = DataConvert.bytes2Float(aBytes, _byteOrder);
            aGridData.data[0][i] = aValue;
        }

        br.close();

        return aGridData;
    } catch (IOException ex) {
        Logger.getLogger(GrADSDataInfo.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}
 
Example 17
Source File: MOOSEFileHandlerTester.java    From ice with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * This operation checks the MOOSEFileHandler to make sure that it can load
 * a MOOSE GetPot file into a TreeComposite.
 */
@Test
public void checkLoadingFromGetPot() {

	// Local Declarations
	String separator = System.getProperty("file.separator");
	String userDir = System.getProperty("user.home") + separator + "ICETests" + separator + "itemData";
	String refFilePath = userDir + separator + "moose_test.i.ref";
	String outFilePath = userDir + separator + "moose_test.i.out";

	// Turn debugging on
	System.setProperty("DebugICE", "on");
	// Create the handler
	MOOSEFileHandler handler = new MOOSEFileHandler();

	// Load the file into a TreeComposite with the Handler
	ArrayList<TreeComposite> potTree = handler.loadFromGetPot(refFilePath);

	// Write an output file based on the tree that was loaded
	handler.dumpInputFile(outFilePath, potTree);

	// Compare the input file to the reference file
	try {
		// Load the reference file into a byte array
		RandomAccessFile refFileRAF = new RandomAccessFile(refFilePath, "r");
		byte[] refBytes = new byte[(int) refFileRAF.length()];
		refFileRAF.read(refBytes);
		// Load the input file into a byte array
		RandomAccessFile outputFileRAF = new RandomAccessFile(outFilePath, "r");
		byte[] outputBytes = new byte[(int) outputFileRAF.length()];
		outputFileRAF.read(outputBytes);
		// Compare the strings
		assertEquals(new String(refBytes), new String(outputBytes));
		// Close everything
		outputFileRAF.close();
		refFileRAF.close();
		// Delete the output file
		File inputFile = new File(outFilePath);
		inputFile.delete();
	} catch (IOException e) {
		e.printStackTrace();
		// One reason that this might happen is because the tree wasn't
		// loaded from the pot file correctly.
		fail();
	}

	return;
}
 
Example 18
Source File: RawDataFileSaveHandler.java    From mzmine2 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Copy the data points file of the raw data file from the temporary folder to the zip file.
 * Create an XML file which contains the description of the same raw data file an copy it into the
 * same zip file.
 * 
 * @param rawDataFile raw data file to be copied
 * @param rawDataSavedName name of the raw data inside the zip file
 * @throws java.io.IOException
 * @throws TransformerConfigurationException
 * @throws SAXException
 */
void writeRawDataFile(RawDataFileImpl rawDataFile, int number)
    throws IOException, TransformerConfigurationException, SAXException {

  numOfScans = rawDataFile.getNumOfScans();

  // Get the structure of the data points file
  dataPointsOffsets = rawDataFile.getDataPointsOffsets();
  dataPointsLengths = rawDataFile.getDataPointsLengths();
  consolidatedDataPointsOffsets = new TreeMap<Integer, Long>();

  // step 1 - save data file
  logger.info("Saving data points of: " + rawDataFile.getName());

  String rawDataSavedName = "Raw data file #" + number + " " + rawDataFile.getName();

  zipOutputStream.putNextEntry(new ZipEntry(rawDataSavedName + ".scans"));

  // We save only those data points that still have a reference in the
  // dataPointsOffset table. Some deleted mass lists may still be present
  // in the data points file, we don't want to copy those.
  long newOffset = 0;
  byte buffer[] = new byte[1 << 20];
  RandomAccessFile dataPointsFile = rawDataFile.getDataPointsFile();
  for (Integer storageID : dataPointsOffsets.keySet()) {

    if (canceled)
      return;

    final long offset = dataPointsOffsets.get(storageID);
    dataPointsFile.seek(offset);

    final int bytes = dataPointsLengths.get(storageID) * 4 * 2;
    consolidatedDataPointsOffsets.put(storageID, newOffset);
    if (buffer.length < bytes) {
      buffer = new byte[bytes * 2];
    }
    dataPointsFile.read(buffer, 0, bytes);
    zipOutputStream.write(buffer, 0, bytes);
    newOffset += bytes;
    progress = 0.9 * ((double) offset / dataPointsFile.length());
  }

  if (canceled)
    return;

  // step 2 - save raw data description
  logger.info("Saving raw data description of: " + rawDataFile.getName());

  zipOutputStream.putNextEntry(new ZipEntry(rawDataSavedName + ".xml"));
  OutputStream finalStream = zipOutputStream;

  StreamResult streamResult = new StreamResult(finalStream);
  SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();

  TransformerHandler hd = tf.newTransformerHandler();
  Transformer serializer = hd.getTransformer();
  serializer.setOutputProperty(OutputKeys.INDENT, "yes");
  serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

  hd.setResult(streamResult);
  hd.startDocument();
  saveRawDataInformation(rawDataFile, hd);
  hd.endDocument();
}
 
Example 19
Source File: GrADSDataInfo.java    From MeteoInfo with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public GridData getGridData_Lat(int timeIdx, int lonIdx, String varName, int levelIdx) {
    try {
        int varIdx = this.getVariableIndex(varName);
        String filePath = DSET;
        int tIdx = timeIdx;
        if (OPTIONS.template) {
            Object[] result = getFilePath_Template(timeIdx);
            filePath = (String) result[0];
            tIdx = (int) result[1];
        }
        RandomAccessFile br = new RandomAccessFile(filePath, "r");
        int i, lNum;
        byte[] aBytes = new byte[4];
        float aValue;

        GridData aGridData = new GridData();
        aGridData.missingValue = this.getMissingValue();
        aGridData.xArray = Y;
        aGridData.yArray = new double[1];
        aGridData.yArray[0] = 0;
        aGridData.data = new double[1][Y.length];

        br.seek(FILEHEADER + tIdx * RecLenPerTime);
        for (i = 0; i < varIdx; i++) {
            lNum = VARDEF.getVars().get(i).getLevelNum();
            if (lNum == 0) {
                lNum = 1;
            }
            br.seek(br.getFilePointer() + lNum * RecordLen);
        }
        br.seek(br.getFilePointer() + levelIdx * RecordLen);
        if (OPTIONS.sequential) {
            br.seek(br.getFilePointer() + 4);
        }
        long aPosition = br.getFilePointer();

        for (i = 0; i < YNum; i++) {
            br.seek(aPosition + i * XNum * 4 + lonIdx * 4);
            br.read(aBytes);
            aValue = DataConvert.bytes2Float(aBytes, _byteOrder);
            aGridData.data[0][i] = aValue;
        }

        br.close();

        return aGridData;
    } catch (IOException ex) {
        Logger.getLogger(GrADSDataInfo.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}
 
Example 20
Source File: NSData.java    From Alite with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Creates a NSData object from a file. Using the files contents as the contents of this NSData object.
 *
 * @param file The file containing the data.
 * @throws FileNotFoundException If the file could not be found.
 * @throws IOException           If the file could not be read.
 */
public NSData(File file) throws IOException {
    bytes = new byte[(int) file.length()];
    RandomAccessFile raf = new RandomAccessFile(file, "r");
    raf.read(bytes);
    raf.close();
}