Java Code Examples for java.io.RandomAccessFile

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project aether-core, under directory /aether-test-util/src/main/java/org/eclipse/aether/internal/test/util/.

Source file: TestFileUtils.java

  33 
vote

public static byte[] getContent(File file) throws IOException {
  RandomAccessFile in=null;
  try {
    in=new RandomAccessFile(file,"r");
    byte[] actual=new byte[(int)in.length()];
    in.readFully(actual);
    return actual;
  }
  finally {
    close(in);
  }
}
 

Example 2

From project AlarmApp-Android, under directory /src/org/alarmapp/util/.

Source file: Device.java

  32 
vote

private static String readInstallationFile(File installation) throws IOException {
  RandomAccessFile f=new RandomAccessFile(installation,"r");
  byte[] bytes=new byte[(int)f.length()];
  f.readFully(bytes);
  f.close();
  return new String(bytes);
}
 

Example 3

From project android-bankdroid, under directory /src/com/liato/bankdroid/lockpattern/.

Source file: LockPatternUtils.java

  32 
vote

/** 
 * Check to see if the user has stored a lock pattern.
 * @return Whether a saved pattern exists.
 */
public boolean savedPatternExists(){
  try {
    RandomAccessFile raf=new RandomAccessFile(sLockPatternFilename,"r");
    byte first=raf.readByte();
    raf.close();
    return true;
  }
 catch (  FileNotFoundException fnfe) {
    return false;
  }
catch (  IOException ioe) {
    return false;
  }
}
 

Example 4

From project android-ocr, under directory /android/src/edu/sfsu/cs/orange/ocr/.

Source file: OcrInitAsyncTask.java

  32 
vote

/** 
 * Returns the uncompressed size for a Gzipped file.
 * @param file Gzipped file to get the size for
 * @return Size when uncompressed, in bytes
 * @throws IOException
 */
private int getGzipSizeUncompressed(File zipFile) throws IOException {
  RandomAccessFile raf=new RandomAccessFile(zipFile,"r");
  raf.seek(raf.length() - 4);
  int b4=raf.read();
  int b3=raf.read();
  int b2=raf.read();
  int b1=raf.read();
  raf.close();
  return (b1 << 24) | (b2 << 16) + (b3 << 8) + b4;
}
 

Example 5

From project android-thaiime, under directory /makedict/src/com/android/inputmethod/latin/.

Source file: BinaryDictInputOutput.java

  32 
vote

/** 
 * Basic test to find out whether the file is a binary dictionary or not. Concretely this only tests the magic number.
 * @param filename The name of the file to test.
 * @return true if it's a binary dictionary, false otherwise
 */
public static boolean isBinaryDictionary(String filename){
  try {
    RandomAccessFile f=new RandomAccessFile(filename,"r");
    return MAGIC_NUMBER == f.readUnsignedShort();
  }
 catch (  FileNotFoundException e) {
    return false;
  }
catch (  IOException e) {
    return false;
  }
}
 

Example 6

From project AndroidBillingLibrary, under directory /AndroidBillingLibrary/src/net/robotmedia/billing/utils/.

Source file: Installation.java

  32 
vote

private static String readInstallationFile(File installation) throws IOException {
  RandomAccessFile f=new RandomAccessFile(installation,"r");
  byte[] bytes=new byte[(int)f.length()];
  f.readFully(bytes);
  f.close();
  return new String(bytes);
}
 

Example 7

From project android_external_guava, under directory /src/com/google/common/io/.

Source file: Files.java

  32 
vote

/** 
 * Maps a file in to memory as per {@link FileChannel#map(java.nio.channels.FileChannel.MapMode,long,long)}using the requested  {@link MapMode}. <p>Files are mapped from offset 0 to  {@code size}. <p>If the mode is  {@link MapMode#READ_WRITE} and the file does not exist,it will be created with the requested  {@code size}. Thus this method is useful for creating memory mapped files which do not yet exist. <p>This only works for files <=  {@link Integer#MAX_VALUE} bytes.
 * @param file the file to map
 * @param mode the mode to use when mapping {@code file}
 * @return a buffer reflecting {@code file}
 * @throws IOException if an I/O error occurs
 * @see FileChannel#map(MapMode,long,long)
 * @since 2010.01.04 <b>tentative</b>
 */
public static MappedByteBuffer map(File file,MapMode mode,long size) throws FileNotFoundException, IOException {
  RandomAccessFile raf=new RandomAccessFile(file,mode == MapMode.READ_ONLY ? "r" : "rw");
  boolean threw=true;
  try {
    MappedByteBuffer mbb=map(raf,mode,size);
    threw=false;
    return mbb;
  }
  finally {
    Closeables.close(raf,threw);
  }
}
 

Example 8

From project android_packages_inputmethods_LatinIME, under directory /tools/makedict/src/com/android/inputmethod/latin/.

Source file: BinaryDictInputOutput.java

  32 
vote

/** 
 * Basic test to find out whether the file is a binary dictionary or not. Concretely this only tests the magic number.
 * @param filename The name of the file to test.
 * @return true if it's a binary dictionary, false otherwise
 */
public static boolean isBinaryDictionary(String filename){
  try {
    RandomAccessFile f=new RandomAccessFile(filename,"r");
    return MAGIC_NUMBER == f.readUnsignedShort();
  }
 catch (  FileNotFoundException e) {
    return false;
  }
catch (  IOException e) {
    return false;
  }
}
 

Example 9

From project avro, under directory /lang/java/mapred/src/test/java/org/apache/avro/mapred/.

Source file: TestGenericJob.java

  32 
vote

@Before public void setup() throws IOException {
  File indir=new File(dir);
  indir.mkdirs();
  File infile=new File(dir + "/in");
  RandomAccessFile file=new RandomAccessFile(infile,"rw");
  file.writeChars("aa bb cc\ndd ee ff\n");
  file.close();
}
 

Example 10

From project bitcask-java, under directory /src/main/java/com/trifork/bitcask/.

Source file: BitCaskLock.java

  32 
vote

private static BitCaskLock lock_acquire(File lockFilename,boolean is_write_lock) throws IOException {
  if (is_write_lock) {
    if (lockFilename.createNewFile() == false) {
      throw new FileAlreadyExistsException(lockFilename);
    }
  }
  RandomAccessFile f=new RandomAccessFile(lockFilename,is_write_lock ? "rws" : "r");
  return new BitCaskLock(f,lockFilename,is_write_lock);
}
 

Example 11

From project flume, under directory /flume-ng-channels/flume-file-channel/src/main/java/org/apache/flume/channel/file/.

Source file: LogFile.java

  32 
vote

private RandomAccessFile checkOut() throws IOException, InterruptedException {
  RandomAccessFile fileHandle=readFileHandles.poll();
  if (fileHandle != null) {
    return fileHandle;
  }
  int remaining=readFileHandles.remainingCapacity();
  if (remaining > 0) {
    LOG.info("Opening " + file + " for read, remaining capacity is "+ remaining);
    return open();
  }
  return readFileHandles.take();
}
 

Example 12

From project Flume-Hive, under directory /src/javatest/com/cloudera/flume/handlers/text/.

Source file: TestTailSourceCursor.java

  32 
vote

/** 
 * This shows that file descriptors from the same RAF are the same, however, two RAFs have different fileDescriptors. This is unfortunate because it means we cannot use FileDescriptors to differentiate by inode, and limits our tail implemenetation
 */
@Test public void testFileDescriptorEquals() throws IOException {
  File f=File.createTempFile("first",".tmp");
  f.deleteOnExit();
  File f2=File.createTempFile("second",".tmp");
  f2.delete();
  f2.deleteOnExit();
  RandomAccessFile raf=new RandomAccessFile(f,"r");
  FileDescriptor fd=raf.getFD();
  RandomAccessFile raf2=new RandomAccessFile(f,"r");
  FileDescriptor fd2=raf2.getFD();
  assertFalse(fd.equals(fd2));
}
 

Example 13

From project flume_1, under directory /flume-core/src/test/java/com/cloudera/flume/handlers/text/.

Source file: TestTailSourceCursor.java

  32 
vote

/** 
 * This shows that file descriptors from the same RAF are the same, however, two RAFs have different fileDescriptors. This is unfortunate because it means we cannot use FileDescriptors to differentiate by inode, and limits our tail implemenetation
 */
@Test public void testFileDescriptorEquals() throws IOException {
  File f=FileUtil.createTempFile("first",".tmp");
  f.deleteOnExit();
  File f2=FileUtil.createTempFile("second",".tmp");
  f2.delete();
  f2.deleteOnExit();
  RandomAccessFile raf=new RandomAccessFile(f,"r");
  FileDescriptor fd=raf.getFD();
  RandomAccessFile raf2=new RandomAccessFile(f,"r");
  FileDescriptor fd2=raf2.getFD();
  assertFalse(fd.equals(fd2));
}
 

Example 14

From project gs-core, under directory /src/org/graphstream/stream/file/.

Source file: FileSinkSWF.java

  32 
vote

@SuppressWarnings("unused") private void initChannelAndBuffer(String path){
  if (channel != null)   closeCurrentChannel();
  try {
    RandomAccessFile file=new RandomAccessFile(path,"rw");
    channel=file.getChannel();
    buffer=ByteBuffer.allocateDirect(BUFFER_SIZE);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    position=0;
    currentSize=0;
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
  }
}
 

Example 15

From project agile, under directory /agile-framework/src/main/java/org/apache/catalina/servlets/.

Source file: DefaultServlet.java

  31 
vote

/** 
 * Handle a partial PUT.  New content specified in request is appended to existing content in oldRevisionContent (if present). This code does not support simultaneous partial updates to the same resource.
 */
protected File executePartialPut(HttpServletRequest req,Range range,String path) throws IOException {
  File tempDir=(File)getServletContext().getAttribute("javax.servlet.context.tempdir");
  String convertedResourcePath=path.replace('/','.');
  File contentFile=new File(tempDir,convertedResourcePath);
  if (contentFile.createNewFile()) {
    contentFile.deleteOnExit();
  }
  RandomAccessFile randAccessContentFile=new RandomAccessFile(contentFile,"rw");
  Resource oldResource=null;
  try {
    Object obj=resources.lookup(path);
    if (obj instanceof Resource)     oldResource=(Resource)obj;
  }
 catch (  NamingException e) {
    ;
  }
  if (oldResource != null) {
    BufferedInputStream bufOldRevStream=new BufferedInputStream(oldResource.streamContent(),BUFFER_SIZE);
    int numBytesRead;
    byte[] copyBuffer=new byte[BUFFER_SIZE];
    while ((numBytesRead=bufOldRevStream.read(copyBuffer)) != -1) {
      randAccessContentFile.write(copyBuffer,0,numBytesRead);
    }
    bufOldRevStream.close();
  }
  randAccessContentFile.setLength(range.length);
  randAccessContentFile.seek(range.start);
  int numBytesRead;
  byte[] transferBuffer=new byte[BUFFER_SIZE];
  BufferedInputStream requestBufInStream=new BufferedInputStream(req.getInputStream(),BUFFER_SIZE);
  while ((numBytesRead=requestBufInStream.read(transferBuffer)) != -1) {
    randAccessContentFile.write(transferBuffer,0,numBytesRead);
  }
  randAccessContentFile.close();
  requestBufInStream.close();
  return contentFile;
}
 

Example 16

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/client/cache/.

Source file: IOUtils.java

  31 
vote

static void copyFile(final File in,final File out) throws IOException {
  RandomAccessFile f1=new RandomAccessFile(in,"r");
  RandomAccessFile f2=new RandomAccessFile(out,"rw");
  try {
    FileChannel c1=f1.getChannel();
    FileChannel c2=f2.getChannel();
    try {
      c1.transferTo(0,f1.length(),c2);
      c1.close();
      c2.close();
    }
 catch (    IOException ex) {
      closeSilently(c1);
      closeSilently(c2);
      throw ex;
    }
    f1.close();
    f2.close();
  }
 catch (  IOException ex) {
    closeSilently(f1);
    closeSilently(f2);
    throw ex;
  }
}
 

Example 17

From project Android, under directory /app/src/main/java/com/github/mobile/.

Source file: RequestWriter.java

  31 
vote

/** 
 * Write request to file
 * @param request
 * @return request
 */
public <V>V write(V request){
  RandomAccessFile dir=null;
  FileLock lock=null;
  ObjectOutputStream output=null;
  try {
    createDirectory(handle.getParentFile());
    dir=new RandomAccessFile(handle,"rw");
    lock=dir.getChannel().lock();
    output=new ObjectOutputStream(new GZIPOutputStream(new FileOutputStream(dir.getFD()),8192));
    output.writeInt(version);
    output.writeObject(request);
  }
 catch (  IOException e) {
    Log.d(TAG,"Exception writing cache " + handle.getName(),e);
    return null;
  }
 finally {
    if (output != null)     try {
      output.close();
    }
 catch (    IOException e) {
      Log.d(TAG,"Exception closing stream",e);
    }
    if (lock != null)     try {
      lock.release();
    }
 catch (    IOException e) {
      Log.d(TAG,"Exception unlocking file",e);
    }
    if (dir != null)     try {
      dir.close();
    }
 catch (    IOException e) {
      Log.d(TAG,"Exception closing file",e);
    }
  }
  return request;
}
 

Example 18

From project android_packages_apps_Gallery2, under directory /gallerycommon/src/com/android/gallery3d/common/.

Source file: BlobCache.java

  31 
vote

public BlobCache(String path,int maxEntries,int maxBytes,boolean reset,int version) throws IOException {
  mIndexFile=new RandomAccessFile(path + ".idx","rw");
  mDataFile0=new RandomAccessFile(path + ".0","rw");
  mDataFile1=new RandomAccessFile(path + ".1","rw");
  mVersion=version;
  if (!reset && loadIndex()) {
    return;
  }
  resetCache(maxEntries,maxBytes);
  if (!loadIndex()) {
    closeAll();
    throw new IOException("unable to load index");
  }
}
 

Example 19

From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/media/.

Source file: DiskCache.java

  31 
vote

public byte[] get(long key,long timestamp){
  Record record=null;
synchronized (mIndexMap) {
    record=mIndexMap.get(key);
  }
  if (record != null) {
    if (record.timestamp < timestamp) {
      Log.i(TAG,"File has been updated to " + timestamp + " since the last time "+ record.timestamp+ " stored in cache.");
      return null;
    }
    try {
      RandomAccessFile chunkFile=getChunkFile(record.chunk);
      if (chunkFile != null) {
        byte[] data=new byte[record.size];
        chunkFile.seek(record.offset);
        chunkFile.readFully(data);
        return data;
      }
    }
 catch (    Exception e) {
      Log.e(TAG,"Unable to read from chunk file");
    }
  }
  return null;
}
 

Example 20

From project apg, under directory /src/org/thialfihar/android/apg/.

Source file: Apg.java

  31 
vote

static void deleteFileSecurely(Context context,File file,ProgressDialogUpdater progress) throws FileNotFoundException, IOException {
  long length=file.length();
  SecureRandom random=new SecureRandom();
  RandomAccessFile raf=new RandomAccessFile(file,"rws");
  raf.seek(0);
  raf.getFilePointer();
  byte[] data=new byte[1 << 16];
  int pos=0;
  String msg=context.getString(R.string.progress_deletingSecurely,file.getName());
  while (pos < length) {
    progress.setProgress(msg,(int)(100 * pos / length),100);
    random.nextBytes(data);
    raf.write(data);
    pos+=data.length;
  }
  raf.close();
  file.delete();
}
 

Example 21

From project aranea, under directory /core/src/main/java/no/dusken/aranea/util/.

Source file: ImageUtils.java

  31 
vote

/** 
 * common This creates an image object from a pdf file, and saves the image to the database The image created is default 640x480, use setMaxHeight, setMaxWidth to change
 * @param pdfFile is the pdf file to use (first page is used)
 * @return the image object created
 * @throws IOException if anything goes wrong
 */
public Image makeThumbnail(File pdfFile) throws IOException {
  if (pdfFile == null || !pdfFile.exists() || !pdfFile.isFile()) {
    throw new IOException("No file");
  }
  log.debug("making thumb for pdf: {}",pdfFile.getAbsolutePath());
  RandomAccessFile raf=new RandomAccessFile(pdfFile,"r");
  FileChannel channel=raf.getChannel();
  ByteBuffer buf=channel.map(FileChannel.MapMode.READ_ONLY,0,channel.size());
  PDFFile pdffile=new PDFFile(buf);
  PDFPage page=pdffile.getPage(0);
  Rectangle rect=new Rectangle(0,0,(int)page.getBBox().getWidth(),(int)page.getBBox().getHeight());
  java.awt.Image img=page.getImage(rect.width,rect.height,rect,null,true,true);
  img=img.getScaledInstance(-1,PDF_HEIGHT,BufferedImage.SCALE_SMOOTH);
  BufferedImage buffScaledPDFImage;
{
    buffScaledPDFImage=new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_INT_RGB);
    Graphics g=buffScaledPDFImage.createGraphics();
    g.drawImage(img,0,0,null);
    g.dispose();
  }
  File tmpImageFile=new File(imageDirectory + "/tmp/" + pdfFile.getName()+ ".png");
  tmpImageFile.getParentFile().mkdirs();
  if (tmpImageFile.exists()) {
    tmpImageFile.delete();
  }
  ImageIO.write(buffScaledPDFImage,"png",tmpImageFile);
  Image i=storeImageService.createImage(tmpImageFile);
  i.setDescription("Thumb for pdf: " + pdfFile.getName());
  i.setExternalSource("From PDF");
  return i;
}
 

Example 22

From project Archimedes, under directory /br.org.archimedes.batik/src/org/apache/batik/svggen/font/.

Source file: Font.java

  31 
vote

/** 
 * @param file The file to read
 * @throws FileNotFoundException Thrown if the file couldn't be found
 */
protected void readFile(File file) throws FileNotFoundException {
  if (!file.exists()) {
    throw new FileNotFoundException("Couldn't load file '" + file.getPath() + "'.");
  }
  try {
    RandomAccessFile raf=new RandomAccessFile(file,"r");
    tableDirectory=new TableDirectory(raf);
    tables=new Table[tableDirectory.getNumTables()];
    for (int i=0; i < tableDirectory.getNumTables(); i++) {
      tables[i]=TableFactory.create(tableDirectory.getEntry(i),raf);
    }
    raf.close();
    os2=(Os2Table)getTable(Table.OS_2);
    cmap=(CmapTable)getTable(Table.cmap);
    glyf=(GlyfTable)getTable(Table.glyf);
    head=(HeadTable)getTable(Table.head);
    hhea=(HheaTable)getTable(Table.hhea);
    hmtx=(HmtxTable)getTable(Table.hmtx);
    loca=(LocaTable)getTable(Table.loca);
    maxp=(MaxpTable)getTable(Table.maxp);
    name=(NameTable)getTable(Table.name);
    post=(PostTable)getTable(Table.post);
    hmtx.init(hhea.getNumberOfHMetrics(),maxp.getNumGlyphs() - hhea.getNumberOfHMetrics());
    loca.init(maxp.getNumGlyphs(),head.getIndexToLocFormat() == 0);
    glyf.init(maxp.getNumGlyphs(),loca);
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 23

From project archive-commons, under directory /archive-commons/src/main/java/org/archive/streamcontext/.

Source file: RandomAccessFileStream.java

  31 
vote

public RandomAccessFileStream(File file,long offset,int readSize) throws IndexOutOfBoundsException, FileNotFoundException, IOException {
  super(offset,readSize);
  raf=new RandomAccessFile(file,"r");
  if (offset > 0) {
    raf.seek(offset);
  }
  this.file=file;
}
 

Example 24

From project autopsy, under directory /thirdparty/pasco2/src/isi/pasco2/io/.

Source file: FastReadIndexFile.java

  31 
vote

public FastReadIndexFile(String fileName) throws FileNotFoundException, IOException {
  File file=new File(fileName);
  FileChannel roChannel=new RandomAccessFile(file,"r").getChannel();
  ByteBuffer roBuf=roChannel.map(FileChannel.MapMode.READ_ONLY,0,(int)roChannel.size());
  byte[] buf=new byte[roBuf.limit()];
  roBuf.get(buf,0,roBuf.limit());
  content=ByteBuffer.wrap(buf);
  roChannel.close();
}
 

Example 25

From project azkaban, under directory /azkaban-common/src/java/azkaban/common/utils/.

Source file: Utils.java

  31 
vote

/** 
 * Read in content of a file and get the last *lineCount* lines. It is equivalent to *tail* command
 * @param filename
 * @param lineCount
 * @param chunkSize
 * @return
 */
public static Vector<String> tail(String filename,int lineCount,int chunkSize){
  try {
    RandomAccessFile file=new RandomAccessFile(filename,"r");
    Vector<String> lastNLines=new Vector<String>();
    long currPos=file.length() - 1;
    long startPos;
    byte[] byteArray=new byte[chunkSize];
    while (true) {
      startPos=currPos - chunkSize;
      if (startPos <= 0) {
        file.seek(0);
        file.read(byteArray,0,(int)currPos);
        parseLinesFromLast(byteArray,0,(int)currPos,lineCount,lastNLines);
        break;
      }
 else {
        file.seek(startPos);
        if (byteArray == null)         byteArray=new byte[chunkSize];
        file.readFully(byteArray);
        if (parseLinesFromLast(byteArray,lineCount,lastNLines)) {
          break;
        }
        currPos=startPos;
      }
    }
    for (int index=lineCount; index < lastNLines.size(); index++)     lastNLines.removeElementAt(index);
    Collections.reverse(lastNLines);
    return lastNLines;
  }
 catch (  Exception e) {
    return null;
  }
}
 

Example 26

From project Baseform-Epanet-Java-Library, under directory /src/org/addition/epanet/msx/.

Source file: Report.java

  31 
vote

public int MSXrpt_write(File outputFile){
  RandomAccessFile raf;
  int magic=0;
  int j;
  if (MSX.Nperiods < 1)   return 0;
  try {
    long flen=outputFile.length();
    raf=new RandomAccessFile(outputFile,"r");
    raf.skipBytes((int)flen - Integer.SIZE / 8);
    magic=raf.readInt();
  }
 catch (  IOException ex) {
    return ErrorCodeType.ERR_IO_OUT_FILE.id;
  }
  if (magic != Constants.MAGICNUMBER)   return ErrorCodeType.ERR_IO_OUT_FILE.id;
  PageNum=1;
  LineNum=1;
  newPage();
  for (j=0; j <= 5; j++)   writeLine(Logo[j]);
  writeLine("");
  writeLine(MSX.Title);
  if (MSX.Statflag == TstatType.SERIES)   createSeriesTables(raf);
 else   createStatsTables(raf);
  writeLine("");
  return 0;
}
 

Example 27

From project bigger-tests, under directory /kernel/src/test/java/org/neo4j/kernel/impl/nioneo/store/.

Source file: TestUpgradeStore.java

  31 
vote

private void setOlderNeoStoreVersion(String path) throws IOException {
  String oldVersion="NeoStore v0.9.6";
  FileChannel channel=new RandomAccessFile(new File(path,NeoStore.DEFAULT_NAME),"rw").getChannel();
  channel.position(channel.size() - UTF8.encode(oldVersion).length);
  ByteBuffer buffer=ByteBuffer.wrap(UTF8.encode(oldVersion));
  channel.write(buffer);
  channel.close();
}
 

Example 28

From project callmeter, under directory /src/de/ub0r/android/callmeter/data/.

Source file: SysClassNet.java

  31 
vote

/** 
 * @param inter interface
 * @param file file (rx or tx)
 * @return bytes received or sent
 */
private static long readLong(final String inter,final String file){
  Log.d(TAG,"readLong(" + inter + ","+ file+ ")");
  StringBuilder sb=new StringBuilder();
  sb.append(SYS_CLASS_NET).append(inter).append(file);
  RandomAccessFile raf=null;
  try {
    raf=getFile(sb.toString());
    String l=raf.readLine();
    Log.d(TAG,"readLong(" + inter + ","+ file+ "): "+ l);
    return Long.valueOf(l);
  }
 catch (  Exception e) {
    Log.e(TAG,e.getMessage() + " / error readding long for inter: " + inter);
    return 0;
  }
 finally {
    if (raf != null) {
      try {
        raf.close();
      }
 catch (      IOException e) {
        Log.e(TAG,null,e);
      }
    }
  }
}
 

Example 29

From project Carolina-Digital-Repository, under directory /persistence/src/test/java/edu/unc/lib/dl/update/.

Source file: AtomDCToMODSFilterTest.java

  31 
vote

@Test public void replaceMODSWithDCTerms() throws Exception {
  InputStream entryPart=new FileInputStream(new File("src/test/resources/atompub/metadataDC.xml"));
  Abdera abdera=new Abdera();
  Parser parser=abdera.getParser();
  Document<Entry> entryDoc=parser.parse(entryPart);
  Entry entry=entryDoc.getRoot();
  AccessClient accessClient=mock(AccessClient.class);
  MIMETypedStream modsStream=new MIMETypedStream();
  RandomAccessFile raf=new RandomAccessFile("src/test/resources/testmods.xml","r");
  byte[] bytes=new byte[(int)raf.length()];
  raf.read(bytes);
  modsStream.setStream(bytes);
  modsStream.setMIMEType("text/xml");
  when(accessClient.getDatastreamDissemination(any(PID.class),eq(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName()),anyString())).thenReturn(modsStream);
  PID pid=new PID("uuid:test");
  PersonAgent user=new PersonAgent("testuser","testuser");
  AtomPubMetadataUIP uip=new AtomPubMetadataUIP(pid,user,UpdateOperation.REPLACE,entry);
  uip.storeOriginalDatastreams(accessClient);
  filter.doFilter(uip);
  Element dcTitleElement=uip.getIncomingData().get(AtomPubMetadataParserUtil.ATOM_DC_DATASTREAM);
  String dcTitle=dcTitleElement.getChildText("title",JDOMNamespaceUtil.DCTERMS_NS);
  Element oldMODSElement=uip.getOriginalData().get(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName());
  String oldMODSTitle=oldMODSElement.getChild("titleInfo",JDOMNamespaceUtil.MODS_V3_NS).getChildText("title",JDOMNamespaceUtil.MODS_V3_NS);
  Element modsElement=uip.getModifiedData().get(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName());
  String newMODSTitle=modsElement.getChild("titleInfo",JDOMNamespaceUtil.MODS_V3_NS).getChildText("title",JDOMNamespaceUtil.MODS_V3_NS);
  assertEquals("Title",dcTitle);
  assertEquals("Hiring and recruitment practices in academic libraries",oldMODSTitle);
  assertEquals(dcTitle,newMODSTitle);
  assertEquals(1,uip.getOriginalData().size());
  assertEquals(1,uip.getModifiedData().size());
  assertEquals(2,uip.getIncomingData().size());
}
 

Example 30

From project CBCJVM, under directory /cbc/CBCJVM/src/cbccore/display/.

Source file: Framebuffer.java

  31 
vote

public Framebuffer(File pipe){
  super(320,240);
  try {
    out=new RandomAccessFile(pipe,"rw");
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
  this.pipe=pipe;
}
 

Example 31

From project ceres, under directory /ceres-binio/src/main/java/com/bc/ceres/binio/.

Source file: DataFormat.java

  31 
vote

/** 
 * Creates a new random access file data context.
 * @param file the file object
 * @param mode the access mode, one of <tt>"r"</tt>, <tt>"rw"</tt>, <tt>"rws"</tt>, or<tt>"rwd"</tt>. See also mode description in  {@link RandomAccessFile#RandomAccessFile(java.io.File,String)}.
 * @return The context.
 * @throws FileNotFoundException If in read-only mode and the file could nt be found.
 */
public DataContext createContext(File file,String mode) throws FileNotFoundException {
  Assert.notNull(file,"file");
  Assert.notNull(mode,"mode");
  final RandomAccessFile raf=new RandomAccessFile(file,mode);
  return new DataContextImpl(this,new RandomAccessFileIOHandler(raf)){
    private boolean disposed;
    @Override public synchronized void dispose(){
      super.dispose();
      disposed=true;
      try {
        raf.close();
      }
 catch (      IOException e) {
      }
    }
    @Override protected void finalize() throws Throwable {
      super.finalize();
      if (!disposed) {
        dispose();
      }
    }
  }
;
}
 

Example 32

From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/datacollection/adaptor/filetailer/.

Source file: LWFTAdaptor.java

  31 
vote

public synchronized boolean tailFile() throws InterruptedException {
  boolean hasMoreData=false;
  try {
    long len=toWatch.length();
    if (len < fileReadOffset) {
      handleShrunkenFile(len);
    }
 else     if (len > fileReadOffset) {
      RandomAccessFile reader=new RandomAccessFile(toWatch,"r");
      slurp(len,reader);
      reader.close();
    }
  }
 catch (  IOException e) {
    log.warn("IOException in tailer",e);
    deregisterAndStop();
  }
  return hasMoreData;
}
 

Example 33

From project cloudify, under directory /USM/src/main/java/org/cloudifysource/usm/tail/.

Source file: RollingFileReader.java

  31 
vote

/** 
 * reads the new lines added to the log file. The method supports RollingFileAppender tailing by not keeping the file open and opening the file only when a changes have been made to it. After reading the changes, the file will be closed and all relevant pointers and properties such as last modified date will be saved for the next iteration. note that the file is being closed in-order to enable the RFA to properly roll the file without having lock issues.
 * @return new lines added to the log file.
 * @throws IOException Indicates the lines were not read because of an IO exception
 */
public String readLines() throws IOException {
  RandomAccessFile randomAccessFile=null;
  try {
    randomAccessFile=new RandomAccessFile(this.file,"r");
    if (this.filePointer > randomAccessFile.length()) {
      this.filePointer=0;
    }
    randomAccessFile.seek(filePointer);
    final byte[] buffer=new byte[(int)randomAccessFile.length() - (int)this.filePointer];
    randomAccessFile.read(buffer);
    this.filePointer=randomAccessFile.length();
    randomAccessFile.close();
    this.lastModified=this.file.lastModified();
    retryCounter=0;
    this.fileLength=file.length();
    return new String(buffer);
  }
 catch (  final FileNotFoundException e) {
    retryCounter++;
    if (retryCounter > DEFAULT_NUMBER_OF_RETRIES) {
      logger.warning("In RollingFileReader: file not found." + DEFAULT_NUMBER_OF_RETRIES + " Retries failed.");
      this.exists=false;
      return "";
    }
    try {
      logger.warning("file not found: " + file.getName() + ". Retring attempt #"+ retryCounter);
      Thread.sleep(TIMEOUT_BETWEEN_RETRIES);
    }
 catch (    final InterruptedException e1) {
      e1.printStackTrace();
    }
    return readLines();
  }
 finally {
    if (randomAccessFile != null) {
      randomAccessFile.close();
    }
  }
}
 

Example 34

From project Collections, under directory /src/main/java/vanilla/java/collections/impl/.

Source file: AbstractHugeContainer.java

  31 
vote

public void ensureCapacity(long size){
  long blocks=(size + allocationSize - 1) / allocationSize;
  while (blocks > allocations.size()) {
    MappedFileChannel mfc=null;
    if (baseDirectory != null) {
      final String name=baseDirectory + "/alloc-" + allocations.size();
      RandomAccessFile raf=null;
      try {
        raf=new RandomAccessFile(name,"rw");
        mfChannels.add(mfc=new MappedFileChannel(raf,allocationByteSize));
      }
 catch (      IOException e) {
        try {
          raf.close();
        }
 catch (        IOException ignored) {
        }
        throw new IllegalStateException("Unable to create allocation " + name,e);
      }
    }
    allocations.add(createAllocation(mfc));
  }
}
 

Example 35

From project commons-compress, under directory /src/main/java/org/apache/commons/compress/archivers/zip/.

Source file: ZipArchiveOutputStream.java

  31 
vote

/** 
 * Creates a new ZIP OutputStream writing to a File.  Will use random access if possible.
 * @param file the file to zip to
 * @throws IOException on error
 */
public ZipArchiveOutputStream(File file) throws IOException {
  OutputStream o=null;
  RandomAccessFile _raf=null;
  try {
    _raf=new RandomAccessFile(file,"rw");
    _raf.setLength(0);
  }
 catch (  IOException e) {
    if (_raf != null) {
      try {
        _raf.close();
      }
 catch (      IOException inner) {
      }
      _raf=null;
    }
    o=new FileOutputStream(file);
  }
  out=o;
  raf=_raf;
}
 

Example 36

From project commons-io, under directory /src/main/java/org/apache/commons/io/filefilter/.

Source file: MagicNumberFileFilter.java

  31 
vote

/** 
 * <p> Accepts the provided file if the file contains the file filter's magic number at the specified offset. </p> <p> If any  {@link IOException}s occur while reading the file, the file will be rejected. </p>
 * @param file the file to accept or reject.
 * @return {@code true} if the file contains the filter's magic number at the specified offset,  {@code false} otherwise.
 */
@Override public boolean accept(File file){
  if (file != null && file.isFile() && file.canRead()) {
    RandomAccessFile randomAccessFile=null;
    try {
      byte[] fileBytes=new byte[this.magicNumbers.length];
      randomAccessFile=new RandomAccessFile(file,"r");
      randomAccessFile.seek(byteOffset);
      int read=randomAccessFile.read(fileBytes);
      if (read != magicNumbers.length) {
        return false;
      }
      return Arrays.equals(this.magicNumbers,fileBytes);
    }
 catch (    IOException ioe) {
    }
 finally {
      IOUtils.closeQuietly(randomAccessFile);
    }
  }
  return false;
}
 

Example 37

From project connectbot, under directory /src/com/trilead/ssh2/.

Source file: KnownHosts.java

  31 
vote

/** 
 * Adds a single public key entry to the a known_hosts file. This method is designed to be used in a  {@link ServerHostKeyVerifier}.
 * @param knownHosts the file where the publickey entry will be appended.
 * @param hostnames a list of hostname patterns - at least one most be specified. Check out theOpenSSH sshd man page for a description of the pattern matching algorithm.
 * @param serverHostKeyAlgorithm as passed to the {@link ServerHostKeyVerifier}.
 * @param serverHostKey as passed to the {@link ServerHostKeyVerifier}.
 * @throws IOException
 */
public final static void addHostkeyToFile(File knownHosts,String[] hostnames,String serverHostKeyAlgorithm,byte[] serverHostKey) throws IOException {
  if ((hostnames == null) || (hostnames.length == 0))   throw new IllegalArgumentException("Need at least one hostname specification");
  if ((serverHostKeyAlgorithm == null) || (serverHostKey == null))   throw new IllegalArgumentException();
  CharArrayWriter writer=new CharArrayWriter();
  for (int i=0; i < hostnames.length; i++) {
    if (i != 0)     writer.write(',');
    writer.write(hostnames[i]);
  }
  writer.write(' ');
  writer.write(serverHostKeyAlgorithm);
  writer.write(' ');
  writer.write(Base64.encode(serverHostKey));
  writer.write("\n");
  char[] entry=writer.toCharArray();
  RandomAccessFile raf=new RandomAccessFile(knownHosts,"rw");
  long len=raf.length();
  if (len > 0) {
    raf.seek(len - 1);
    int last=raf.read();
    if (last != '\n')     raf.write('\n');
  }
  raf.write(new String(entry).getBytes("ISO-8859-1"));
  raf.close();
}
 

Example 38

From project craftbook, under directory /oldsrc/commonrefactor/com/sk89q/craftbook/mech/.

Source file: BookReader.java

  31 
vote

/** 
 * Get a line from the book lines file.
 * @return
 * @throws IOException
 */
private static String getBookLine() throws IOException {
  RandomAccessFile file=new RandomAccessFile(new File("craftbook-books.txt"),"r");
  long len=file.length();
  byte[] data=new byte[500];
  for (int tries=0; tries < 3; tries++) {
    int j=rand.nextInt((int)len);
    if (tries == 2) {
      j=0;
    }
    file.seek(j);
    file.read(data);
    StringBuilder buffer=new StringBuilder();
    boolean found=j == 0;
    byte last=0;
    for (int i=0; i < data.length; i++) {
      if (found) {
        if (data[i] == 10 || data[i] == 13 || i >= len) {
          if (last != 10 && last != 13) {
            return buffer.toString();
          }
        }
 else {
          buffer.appendCodePoint(data[i]);
        }
      }
 else       if (data[i] == 10 || data[i] == 13) {
        found=true;
      }
      last=data[i];
    }
  }
  return null;
}
 

Example 39

From project D2-Java-Persistence, under directory /src/main/java/org/d2/plugins/localfile/.

Source file: FileReadWriteLock.java

  31 
vote

public synchronized void acquireReadLock(){
  if (rwl.getWriteHoldCount() > 0)   throw new RuntimeException("Cannot acquire read lock - write lock already held by this thread");
  rwl.readLock().lock();
  try {
    if (rwl.getReadLockCount() == 1 && rwl.getReadHoldCount() == 1 && channel == null) {
      channel=new RandomAccessFile(file,"rw").getChannel();
      fileLock=channel.lock(0L,Long.MAX_VALUE,true);
    }
  }
 catch (  IOException e) {
    throw Util.wrap(e);
  }
}
 

Example 40

From project dawn-common, under directory /org.dawb.common.util/src/org/dawb/common/util/io/.

Source file: FileUtils.java

  31 
vote

/** 
 * @param tmp
 * @param sizeInB
 * @return boolean
 * @throws IOException
 */
public static boolean isDiskSpaceAvaliable(final File tmp,final long sizeInB) throws IOException {
  if (!tmp.getParentFile().exists()) {
    tmp.getParentFile().mkdirs();
  }
  if (!tmp.exists()) {
    tmp.createNewFile();
  }
  RandomAccessFile raf=null;
  try {
    raf=new RandomAccessFile(tmp,"rw");
    raf.setLength(sizeInB);
    return true;
  }
 catch (  IOException ioe) {
    return false;
  }
 finally {
    if (raf != null) {
      raf.close();
    }
    tmp.delete();
  }
}
 

Example 41

From project dawn-isenciaui, under directory /com.isencia.passerelle.workbench.model.ui/src/main/java/com/isencia/passerelle/workbench/model/ui/utils/.

Source file: FileUtils.java

  31 
vote

/** 
 * @param tmp
 * @param sizeInB
 * @return boolean
 * @throws IOException
 */
public static boolean isDiskSpaceAvaliable(final File tmp,final long sizeInB) throws IOException {
  if (!tmp.getParentFile().exists()) {
    tmp.getParentFile().mkdirs();
  }
  if (!tmp.exists()) {
    tmp.createNewFile();
  }
  RandomAccessFile raf=null;
  try {
    raf=new RandomAccessFile(tmp,"rw");
    raf.setLength(sizeInB);
    return true;
  }
 catch (  IOException ioe) {
    return false;
  }
 finally {
    if (raf != null) {
      raf.close();
    }
    tmp.delete();
  }
}
 

Example 42

From project dcm4che, under directory /dcm4che-core/src/main/java/org/dcm4che/media/.

Source file: DicomDirReader.java

  31 
vote

protected DicomDirReader(File file,String mode) throws IOException {
  this.file=file;
  this.raf=new RandomAccessFile(file,mode);
  try {
    this.in=new DicomInputStream(new RAFInputStreamAdapter(raf));
    this.fmi=in.readFileMetaInformation();
    this.fsInfo=in.readDataset(-1,Tag.DirectoryRecordSequence);
    if (in.tag() != Tag.DirectoryRecordSequence)     throw new IOException("Missing Directory Record Sequence");
  }
 catch (  IOException e) {
    SafeClose.close(raf);
    throw e;
  }
}
 

Example 43

From project Diver, under directory /ca.uvic.chisel.javasketch/src/ca/uvic/chisel/javasketch/persistence/internal/logs/.

Source file: TraceLog.java

  31 
vote

/** 
 * Creates a new trace log for reading
 * @param file
 * @throws FileNotFoundException
 */
public TraceLog(File file) throws IOException {
  if (reader == null) {
    RandomAccessFile ra=new RandomAccessFile(file,"r");
    int count=0;
    try {
      while (count < 3 && ra.length() <= 4) {
        try {
          Thread.sleep(200);
        }
 catch (        InterruptedException e) {
          Thread.interrupted();
        }
        count++;
      }
      if (count >= 3) {
        throw new IOException("No data in file " + file.getAbsolutePath());
      }
      int type=ra.readShort();
      if (type != TraceLogEvent.HEADER) {
        throw new IOException("Unknown file format.");
      }
      int version=ra.readShort();
      ra.seek(0);
      this.reader=EventReader.getReader(version,ra);
    }
 catch (    IllegalArgumentException e) {
      ra.close();
      throw new IOException("Bad file version",e);
    }
catch (    IOException e) {
      ra.close();
      throw e;
    }
  }
}
 

Example 44

From project dolphin, under directory /dolphinmaple/src/com/tan/util/.

Source file: TestDownFile.java

  31 
vote

public static void main(String[] args){
  String sURL="http://localhost:8080/1.txt";
  int nStartPos=0;
  int nRead=0;
  String sName="book.txt";
  String sPath="d:\\temp";
  try {
    URL url=new URL(sURL);
    HttpURLConnection httpConnection=(HttpURLConnection)url.openConnection();
    long nEndPos=getFileSize(sURL);
    RandomAccessFile oSavedFile=new RandomAccessFile(sPath + "\\" + sName,"rw");
    httpConnection.setRequestProperty("User-Agent","Internet Explorer");
    String sProperty="bytes=" + nStartPos + "-";
    httpConnection.setRequestProperty("RANGE",sProperty);
    InputStream input=httpConnection.getInputStream();
    byte[] b=new byte[1024];
    while ((nRead=input.read(b,0,1024)) > 0 && nStartPos < nEndPos) {
      oSavedFile.write(b,0,nRead);
      nStartPos+=nRead;
    }
    httpConnection.disconnect();
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 45

From project enterprise, under directory /com/src/main/java/org/neo4j/com/.

Source file: ToFileStoreWriter.java

  31 
vote

public void write(String path,ReadableByteChannel data,ByteBuffer temporaryBuffer,boolean hasData) throws IOException {
  try {
    temporaryBuffer.clear();
    File file=new File(basePath,path);
    RandomAccessFile randomAccessFile=null;
    try {
      file.getParentFile().mkdirs();
      randomAccessFile=new RandomAccessFile(file,"rw");
      if (hasData) {
        FileChannel channel=randomAccessFile.getChannel();
        while (data.read(temporaryBuffer) >= 0) {
          temporaryBuffer.flip();
          channel.write(temporaryBuffer);
          temporaryBuffer.clear();
        }
      }
    }
  finally {
      if (randomAccessFile != null) {
        randomAccessFile.close();
      }
    }
  }
 catch (  Throwable t) {
    t.printStackTrace();
    throw new IOException(t);
  }
}
 

Example 46

From project fire-samples, under directory /cache-demo/src/main/java/demo/vmware/util/.

Source file: PersistenceDirectoryGenerator.java

  31 
vote

private boolean lock(File directory){
  String name="node.lock";
  File lockfile=new File(directory,name);
  lockfile.deleteOnExit();
  try {
    RandomAccessFile rf=new RandomAccessFile(lockfile,"rw");
    FileChannel fc=rf.getChannel();
    System.err.println("Attempting to lock:" + lockfile);
    lock=fc.tryLock();
    System.err.println("Locked:" + lock);
    if (lock != null) {
      File f=new File(directory,"BACKUPdefault.if");
      boolean result=true;
      if (f.exists()) {
        result=f.delete();
      }
      f=new File(directory,"DRLK_IFdefault.lk");
      if (result && f.exists()) {
        result=f.delete();
      }
      return result;
    }
  }
 catch (  IOException x) {
  }
catch (  OverlappingFileLockException e) {
  }
  return false;
}
 

Example 47

From project fits_1, under directory /src/edu/harvard/hul/ois/fits/tools/ffident/.

Source file: FormatIdentification.java

  31 
vote

public FormatDescription identify(File file){
  if (!file.isFile()) {
    return null;
  }
  long size=file.length();
  int numBytes;
  if (size > minBufferSize) {
    numBytes=minBufferSize;
  }
 else {
    numBytes=(int)size;
  }
  byte[] data=new byte[numBytes];
  RandomAccessFile in=null;
  try {
    in=new RandomAccessFile(file,"r");
    in.readFully(data);
    in.close();
  }
 catch (  IOException ioe) {
    return null;
  }
 finally {
    try {
      if (in != null) {
        in.close();
      }
    }
 catch (    IOException ioe) {
    }
  }
  return identify(data);
}
 

Example 48

From project flazr, under directory /src/main/java/com/flazr/io/.

Source file: RandomAccessFileReader.java

  31 
vote

public RandomAccessFileReader(final File file){
  absolutePath=file.getAbsolutePath();
  try {
    in=new RandomAccessFile(file,"r");
    fileSize=in.length();
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 49

From project g414-hash, under directory /src/main/java/com/g414/hash/file/.

Source file: HashFileBuilder.java

  31 
vote

/** 
 * Finishes building the HashFile.
 */
public synchronized void finish() throws IOException {
  this.isFinished=true;
  this.dataFile.close();
  for (  DataOutputStream stream : this.hashCodeList) {
    stream.close();
  }
  long[] bucketOffsets=computeBucketOffsets(this.bucketCounts);
  long pos=this.dataFilePosition;
  RandomAccessFile dataFileRandomAccess=new RandomAccessFile(dataFilePath,"rw");
  dataFileRandomAccess.seek(dataFilePosition);
  writeHashTable(radixFilePrefix,this.bucketPower,bucketOffsets,bucketCounts,dataFileRandomAccess);
  ByteBuffer slotTable=getBucketPositionTable(bucketOffsets,this.bucketCounts,pos);
  dataFileRandomAccess.seek(0L);
  dataFileRandomAccess.writeBytes(Calculations.MAGIC);
  dataFileRandomAccess.writeLong(Calculations.VERSION);
  dataFileRandomAccess.writeLong(this.count);
  dataFileRandomAccess.writeInt(this.bucketPower);
  dataFileRandomAccess.write(slotTable.array());
  for (int i=0; i < Calculations.RADIX_FILE_COUNT; i++) {
    String filename=String.format("%s%02X",radixFilePrefix,i);
    (new File(filename)).delete();
  }
  dataFileRandomAccess.close();
}
 

Example 50

From project gda-common, under directory /uk.ac.gda.common/src/uk/ac/gda/util/io/.

Source file: FileUtils.java

  31 
vote

/** 
 * @param tmp
 * @param sizeInB
 * @return boolean
 * @throws IOException
 */
public static boolean isDiskSpaceAvaliable(final File tmp,final long sizeInB) throws IOException {
  if (!tmp.getParentFile().exists()) {
    tmp.getParentFile().mkdirs();
  }
  if (!tmp.exists()) {
    tmp.createNewFile();
  }
  RandomAccessFile raf=null;
  try {
    raf=new RandomAccessFile(tmp,"rw");
    raf.setLength(sizeInB);
    return true;
  }
 catch (  IOException ioe) {
    return false;
  }
 finally {
    if (raf != null) {
      raf.close();
    }
    tmp.delete();
  }
}
 

Example 51

From project gh4a, under directory /src/com/github/mobile/util/.

Source file: ImageUtils.java

  31 
vote

/** 
 * Get a bitmap from the image path
 * @param imagePath
 * @param sampleSize
 * @return bitmap or null if read fails
 */
public static Bitmap getBitmap(final String imagePath,int sampleSize){
  final Options options=new Options();
  options.inDither=false;
  options.inSampleSize=sampleSize;
  RandomAccessFile file=null;
  try {
    file=new RandomAccessFile(imagePath,"r");
    return BitmapFactory.decodeFileDescriptor(file.getFD(),null,options);
  }
 catch (  IOException e) {
    Log.d(TAG,e.getMessage(),e);
    return null;
  }
 finally {
    if (file != null)     try {
      file.close();
    }
 catch (    IOException e) {
      Log.d(TAG,e.getMessage(),e);
    }
  }
}
 

Example 52

From project activemq-apollo, under directory /apollo-util/src/main/scala/org/apache/activemq/apollo/util/.

Source file: LockFile.java

  30 
vote

/** 
 * @throws IOException
 */
synchronized public void lock() throws IOException {
  if (DISABLE_FILE_LOCK) {
    return;
  }
  if (lockCounter > 0) {
    return;
  }
  IOHelper.mkdirs(file.getParentFile());
  if (lock == null) {
    readFile=new RandomAccessFile(file,"rw");
    IOException reason=null;
    try {
      lock=readFile.getChannel().tryLock();
    }
 catch (    OverlappingFileLockException e) {
      reason=IOExceptionSupport.create("File '" + file + "' could not be locked.",e);
    }
    if (lock != null) {
      lockCounter++;
    }
 else {
      closeReadFile();
      if (reason != null) {
        throw reason;
      }
      throw new IOException("File '" + file + "' could not be locked.");
    }
  }
}
 

Example 53

From project Android-MapForgeFragment, under directory /library-common/src/com/jakewharton/android/mapsforge_fragment/.

Source file: MapDatabase.java

  30 
vote

/** 
 * Opens the given map file, reads its header data and validates them.
 * @param fileName the path to the map file.
 * @return true if the file could be opened and is a valid map file, false otherwise.
 * @throws IllegalArgumentException if the given fileName is null.
 */
public boolean openFile(String fileName){
  try {
    closeFile();
    if (fileName == null) {
      throw new IllegalArgumentException("fileName must not be null");
    }
    File file=new File(fileName);
    if (!file.exists()) {
      Logger.debug("file does not exist: " + fileName);
      return false;
    }
 else     if (!file.isFile()) {
      Logger.debug("not a file: " + fileName);
      return false;
    }
 else     if (!file.canRead()) {
      Logger.debug("cannot read file: " + fileName);
      return false;
    }
    this.inputFile=new RandomAccessFile(file,"r");
    this.fileSize=this.inputFile.length();
    if (!processFileHeader()) {
      closeFile();
      return false;
    }
    return true;
  }
 catch (  IOException e) {
    Logger.exception(e);
    closeFile();
    return false;
  }
}
 

Example 54

From project CommitCoin, under directory /src/com/google/bitcoin/store/.

Source file: BoundedOverheadBlockStore.java

  30 
vote

private void createNewStore(NetworkParameters params,File file) throws BlockStoreException {
  blockCache.clear();
  try {
    if (file.exists()) {
      if (!file.delete())       throw new BlockStoreException("Could not delete old store in order to recreate it");
    }
    this.file=new RandomAccessFile(file,"rwd");
    this.channel=this.file.getChannel();
    lock();
    this.file.write(FILE_FORMAT_VERSION);
  }
 catch (  IOException e1) {
    throw new BlockStoreException(e1);
  }
  try {
    Block genesis=params.genesisBlock.cloneAsHeader();
    StoredBlock storedGenesis=new StoredBlock(genesis,genesis.getWork(),0);
    this.chainHead=storedGenesis.getHeader().getHash();
    this.file.write(this.chainHead.getBytes());
    put(storedGenesis);
  }
 catch (  VerificationException e1) {
    throw new RuntimeException(e1);
  }
catch (  IOException e) {
    throw new BlockStoreException(e);
  }
}
 

Example 55

From project eik, under directory /plugins/info.evanchik.karaf.app/src/main/java/org/apache/felix/karaf/main/.

Source file: SimpleFileLock.java

  30 
vote

public SimpleFileLock(Properties props){
  try {
    LOG.addHandler(BootstrapLogManager.getDefaultHandler());
    String lock=props.getProperty(PROPERTY_LOCK_DIR);
    if (lock != null) {
      File karafLock=getKarafLock(new File(lock),props);
      props.setProperty(PROPERTY_LOCK_DIR,karafLock.getPath());
    }
 else {
      props.setProperty(PROPERTY_LOCK_DIR,System.getProperty(PROP_KARAF_BASE));
    }
    File base=new File(props.getProperty(PROPERTY_LOCK_DIR));
    lockFile=new RandomAccessFile(new File(base,"lock"),"rw");
  }
 catch (  IOException e) {
    throw new RuntimeException("Could not create file lock",e);
  }
}
 

Example 56

From project encog-java-core, under directory /src/main/java/org/encog/ml/data/buffer/.

Source file: EncogEGBFile.java

  30 
vote

/** 
 * Create a new RGB file.
 * @param theInputCount The input count.
 * @param theIdealCount The ideal count.
 */
public void create(final int theInputCount,final int theIdealCount){
  try {
    this.inputCount=theInputCount;
    this.idealCount=theIdealCount;
    final double[] input=new double[inputCount];
    final double[] ideal=new double[idealCount];
    this.file.delete();
    this.raf=new RandomAccessFile(this.file,"rw");
    this.raf.setLength(0);
    this.fc=this.raf.getChannel();
    this.headerBuffer.clear();
    this.headerBuffer.order(ByteOrder.LITTLE_ENDIAN);
    this.headerBuffer.put((byte)'E');
    this.headerBuffer.put((byte)'N');
    this.headerBuffer.put((byte)'C');
    this.headerBuffer.put((byte)'O');
    this.headerBuffer.put((byte)'G');
    this.headerBuffer.put((byte)'-');
    this.headerBuffer.put((byte)'0');
    this.headerBuffer.put((byte)'0');
    this.headerBuffer.putDouble(input.length);
    this.headerBuffer.putDouble(ideal.length);
    this.numberOfRecords=0;
    this.recordCount=this.inputCount + this.idealCount + 1;
    this.recordSize=this.recordCount * EncogEGBFile.DOUBLE_SIZE;
    this.recordBuffer=ByteBuffer.allocate(this.recordSize);
    this.headerBuffer.flip();
    this.fc.write(this.headerBuffer);
  }
 catch (  final IOException ex) {
    throw new BufferedDataError(ex);
  }
}
 

Example 57

From project gecko, under directory /src/test/java/com/taobao/gecko/service/impl/.

Source file: TransferFileUnitTest.java

  30 
vote

@Test public void testTransferFile() throws Exception {
  final ServerConfig serverConfig=new ServerConfig();
  serverConfig.setWireFormatType(new NotifyWireFormatType());
  serverConfig.setPort(this.port++);
  final RemotingServer server=RemotingFactory.bind(serverConfig);
  final String url=server.getConnectURI().toString();
  final File file=File.createTempFile("remoting","test");
  file.delete();
  final FileChannel channel=new RandomAccessFile(file,"rw").getChannel();
  final ByteBuffer buff=ByteBuffer.allocate(7);
  buff.put("hello".getBytes());
  buff.flip();
  channel.write(buff);
  channel.force(true);
  server.registerProcessor(NotifyDummyRequestCommand.class,new RequestProcessor<NotifyDummyRequestCommand>(){
    public ThreadPoolExecutor getExecutor(){
      return null;
    }
    public void handleRequest(    final NotifyDummyRequestCommand request,    final Connection conn){
      conn.transferFrom(IoBuffer.wrap("head ".getBytes()),IoBuffer.wrap(" tail\r\n".getBytes()),channel,0,7);
    }
  }
);
  final Socket socket=new Socket();
  socket.connect(server.getInetSocketAddress());
  final DataOutputStream out=new DataOutputStream(socket.getOutputStream());
  out.writeByte(0x80);
  out.writeByte(0x13);
  out.writeShort(0);
  out.writeInt(0);
  out.writeInt(0);
  out.flush();
  final BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
  final String line=reader.readLine();
  assertEquals("head hello tail",line);
  server.stop();
  socket.close();
  channel.close();
  file.delete();
}
 

Example 58

From project cloudhopper-commons-util, under directory /src/main/java/com/cloudhopper/commons/util/.

Source file: FastByteArrayOutputStream.java

  29 
vote

public void writeTo(RandomAccessFile out) throws IOException {
  if (buffers != null) {
    Iterator iter=buffers.iterator();
    while (iter.hasNext()) {
      byte[] bytes=(byte[])iter.next();
      out.write(bytes,0,blockSize);
    }
  }
  out.write(buffer,0,index);
}
 

Example 59

From project fasthat, under directory /src/com/sun/tools/hat/internal/parser/.

Source file: MappedReadBuffer.java

  29 
vote

static ReadBuffer create(RandomAccessFile file) throws IOException {
  FileChannel ch=file.getChannel();
  long size=ch.size();
  if (canUseFileMap() && (size <= Integer.MAX_VALUE)) {
    MappedByteBuffer buf;
    try {
      buf=ch.map(FileChannel.MapMode.READ_ONLY,0,size);
      ch.close();
      return new MappedReadBuffer(buf);
    }
 catch (    IOException exp) {
      exp.printStackTrace();
      System.err.println("File mapping failed, will use direct read");
    }
  }
  return new FileReadBuffer(file);
}