001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.imaging.common.bytesource; 018 019import java.io.BufferedInputStream; 020import java.io.ByteArrayOutputStream; 021import java.io.File; 022import java.io.FileInputStream; 023import java.io.IOException; 024import java.io.InputStream; 025import java.io.RandomAccessFile; 026 027import org.apache.commons.imaging.common.BinaryFunctions; 028 029public class ByteSourceFile extends ByteSource { 030 private final File file; 031 032 public ByteSourceFile(final File file) { 033 super(file.getName()); 034 this.file = file; 035 } 036 037 @Override 038 public InputStream getInputStream() throws IOException { 039 return new BufferedInputStream(new FileInputStream(file)); 040 } 041 042 @Override 043 public byte[] getBlock(final long start, final int length) throws IOException { 044 try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { 045 // We include a separate check for int overflow. 046 if ((start < 0) || (length < 0) || (start + length < 0) 047 || (start + length > raf.length())) { 048 throw new IOException("Could not read block (block start: " 049 + start + ", block length: " + length 050 + ", data length: " + raf.length() + ")."); 051 } 052 053 return BinaryFunctions.getRAFBytes(raf, start, length, 054 "Could not read value from file"); 055 } 056 } 057 058 @Override 059 public long getLength() { 060 return file.length(); 061 } 062 063 @Override 064 public byte[] getAll() throws IOException { 065 final ByteArrayOutputStream baos = new ByteArrayOutputStream(); 066 067 try (InputStream is = getInputStream()) { 068 final byte[] buffer = new byte[1024]; 069 int read; 070 while ((read = is.read(buffer)) > 0) { 071 baos.write(buffer, 0, read); 072 } 073 return baos.toByteArray(); 074 } 075 } 076 077 @Override 078 public String getDescription() { 079 return "File: '" + file.getAbsolutePath() + "'"; 080 } 081 082}