List of usage examples for java.io RandomAccessFile RandomAccessFile
public RandomAccessFile(File file, String mode) throws FileNotFoundException
From source file:com.aol.advertising.qiao.util.CommonUtils.java
protected static RandomAccessFile openFile(File file) throws InterruptedException { RandomAccessFile reader = null; try {// www . j a va 2 s .co m reader = new RandomAccessFile(file, "r"); return reader; } catch (FileNotFoundException e) { return null; } }
From source file:ValidateLicenseHeaders.java
/** * Read the first comment upto the package ...; statement * //from ww w .ja v a 2 s. com * @param javaFile */ static void parseHeader(File javaFile) throws IOException { totalCount++; RandomAccessFile raf = new RandomAccessFile(javaFile, "rw"); String line = raf.readLine(); StringBuffer tmp = new StringBuffer(); long endOfHeader = 0; boolean packageOrImport = false; while (line != null) { long nextEOH = raf.getFilePointer(); line = line.trim(); // Ignore any single line comments if (line.startsWith("//")) { line = raf.readLine(); continue; } // If this is a package/import/class/interface statement break if (line.startsWith("package") || line.startsWith("import") || line.indexOf("class") >= 0 || line.indexOf("interface") >= 0) { packageOrImport = true; break; } // Update the current end of header marker endOfHeader = nextEOH; if (line.startsWith("/**")) tmp.append(line.substring(3)); else if (line.startsWith("/*")) tmp.append(line.substring(2)); else if (line.startsWith("*")) tmp.append(line.substring(1)); else tmp.append(line); tmp.append(' '); line = raf.readLine(); } raf.close(); if (tmp.length() == 0 || packageOrImport == false) { addDefaultHeader(javaFile); return; } String text = tmp.toString(); // Replace all duplicate whitespace with a single space text = text.replaceAll("[\\s*]+", " "); text = text.toLowerCase().trim(); // Replace any copyright date0-date1,date2 with copyright ... text = text.replaceAll(COPYRIGHT_REGEX, "..."); if (tmp.length() == 0) { addDefaultHeader(javaFile); return; } // Search for a matching header boolean matches = false; String matchID = null; Iterator iter = licenseHeaders.entrySet().iterator(); escape: while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String key = (String) entry.getKey(); List list = (List) entry.getValue(); Iterator jiter = list.iterator(); while (jiter.hasNext()) { LicenseHeader lh = (LicenseHeader) jiter.next(); if (text.startsWith(lh.text)) { matches = true; matchID = lh.id; lh.count++; lh.usage.add(javaFile); if (log.isLoggable(Level.FINE)) log.fine(javaFile + " matches copyright key=" + key + ", id=" + lh.id); break escape; } } } text = null; tmp.setLength(0); if (matches == false) invalidheaders.add(javaFile); else if (matchID.startsWith("jboss") && matchID.endsWith("#0") == false) { // This is a legacy jboss head that needs to be updated to the default replaceHeader(javaFile, endOfHeader); jbossCount++; } }
From source file:com.zimbra.cs.redolog.util.RedoLogVerify.java
public boolean scanLog(File logfile) throws IOException { boolean good = false; FileLogReader logReader = new FileLogReader(logfile, false); logReader.open();//from w ww .ja v a2 s . com if (!mParams.quiet) { FileHeader header = logReader.getHeader(); mOut.println("HEADER"); mOut.println("------"); mOut.print(header); mOut.println("------"); } boolean hasMailboxIdsFilter = !mParams.mboxIds.isEmpty(); RedoableOp op = null; long lastPosition = 0; long lastOpStartOffset = 0; try { while ((op = logReader.getNextOp()) != null) { lastOpStartOffset = logReader.getLastOpStartOffset(); lastPosition = logReader.position(); if (hasMailboxIdsFilter) { int mboxId = op.getMailboxId(); if (op instanceof StoreIncomingBlob) { List<Integer> list = ((StoreIncomingBlob) op).getMailboxIdList(); if (list != null) { boolean match = false; for (Integer mid : list) { if (mParams.mboxIds.contains(mid)) { match = true; break; } } if (!match) continue; } // If list==null, it's a store incoming blob op targeted at unknown set of mailboxes. // It applies to our filtered mailboxes. } else if (!mParams.mboxIds.contains(mboxId)) { continue; } } if (!mParams.quiet) { printOp(mOut, op, mParams.hideOffset, lastOpStartOffset, lastPosition - lastOpStartOffset); if (mParams.showBlob) { InputStream dataStream = op.getAdditionalDataStream(); if (dataStream != null) { mOut.println("<START OF BLOB>"); ByteUtil.copy(dataStream, true, mOut, false); mOut.println(); mOut.println("<END OF BLOB>"); } } } } good = true; } catch (IOException e) { // The IOException could be a real I/O problem or it could mean // there was a server crash previously and there were half-written // log entries. mOut.println(); mOut.printf("Error while parsing data starting at offset 0x%08x", lastPosition); mOut.println(); long size = logReader.getSize(); long diff = size - lastPosition; mOut.printf("%d bytes remaining in the file", diff); mOut.println(); mOut.println(); if (op != null) { mOut.println("Last suceessfully parsed redo op:"); printOp(mOut, op, false, lastOpStartOffset, lastPosition - lastOpStartOffset); mOut.println(); } // hexdump data around the bad bytes int bytesPerLine = 16; int linesBefore = 10; int linesAfter = 10; long startPos = Math.max(lastPosition - (lastPosition % bytesPerLine) - linesBefore * bytesPerLine, 0); int count = (int) Math.min((linesBefore + linesAfter + 1) * bytesPerLine, lastPosition - startPos + diff); RandomAccessFile raf = null; try { raf = new RandomAccessFile(logfile, "r"); raf.seek(startPos); byte buf[] = new byte[count]; raf.read(buf, 0, count); mOut.printf("Data near error offset %08x:", lastPosition); mOut.println(); hexdump(mOut, buf, 0, count, startPos, lastPosition); mOut.println(); } catch (IOException eh) { mOut.println("Error opening log file " + logfile.getAbsolutePath() + " for hexdump"); eh.printStackTrace(mOut); } finally { if (raf != null) raf.close(); } throw e; } finally { logReader.close(); } return good; }
From source file:dk.statsbiblioteket.util.LineReaderTest.java
public void dumpSpeedRA() throws Exception { Random random = new Random(); RandomAccessFile ra = new RandomAccessFile(logfile, "r"); long[] pos = getPositions(); // Warming up for (int i = 0; i < 1000; i++) { ra.seek(pos[random.nextInt(LINES)]); ra.readLine();// w w w . j a v a2 s. com } Profiler profiler = new Profiler(); profiler.setExpectedTotal(SPEED_SEEKS); for (int i = 0; i < SPEED_SEEKS; i++) { ra.seek(pos[random.nextInt(LINES)]); ra.readLine(); profiler.beat(); } System.out.println("Performed " + SPEED_SEEKS + " RA seeks & " + "reads at " + Math.round(profiler.getBps(false)) + " seeks/second"); }
From source file:com.all.login.LoginLock.java
public static final boolean getLock() { FileLock lock = null;// w ww. ja va 2 s .c o m try { File file = new File("allClientLock"); FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); for (int i = 0; i < 10 && lock == null; i++) { try { lock = channel.tryLock(); } catch (Exception e) { } if (lock == null) { log.warn( "All application is currently running unable to continue... try " + (i + 1) + " of 10"); } Thread.sleep(1000); } } catch (Exception e) { return false; } return lock != null; }
From source file:info.snowhow.plugin.RecorderService.java
@Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i(LOG_TAG, "Received start id " + startId + ": " + intent); if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { showNoGPSAlert();/*from w w w. j a v a2 s . c o m*/ } runningID = startId; // We want this service to continue running until it is explicitly // stopped, so return sticky. if (intent == null) { tf = sharedPref.getString("runningTrackFile", ""); Log.w(LOG_TAG, "Intent is null, trying to continue to write to file " + tf + " lm " + locationManager); minimumPrecision = sharedPref.getFloat("runningPrecision", 0); distanceChange = sharedPref.getLong("runningDistanceChange", MINIMUM_DISTANCE_CHANGE_FOR_UPDATES); updateTime = sharedPref.getLong("runningUpdateTime", MINIMUM_TIME_BETWEEN_UPDATES); updateTimeFast = sharedPref.getLong("runningUpdateTimeFast", MINIMUM_TIME_BETWEEN_UPDATES_FAST); speedLimit = sharedPref.getLong("runningSpeedLimit", SPEED_LIMIT); adaptiveRecording = sharedPref.getBoolean("adaptiveRecording", false); int count = sharedPref.getInt("count", 0); if (count > 0) { firstPoint = false; } if (tf == null || tf == "") { Log.e(LOG_TAG, "No trackfile found ... exit clean here"); cleanUp(); return START_NOT_STICKY; } } else { tf = intent.getStringExtra("fileName"); Log.d(LOG_TAG, "FILENAME for recording is " + tf); minimumPrecision = intent.getFloatExtra("precision", 0); distanceChange = intent.getLongExtra("distance_change", MINIMUM_DISTANCE_CHANGE_FOR_UPDATES); updateTime = intent.getLongExtra("update_time", MINIMUM_TIME_BETWEEN_UPDATES); updateTimeFast = intent.getLongExtra("update_time_fast", MINIMUM_TIME_BETWEEN_UPDATES_FAST); speedLimit = intent.getLongExtra("speed_limit", SPEED_LIMIT); adaptiveRecording = intent.getBooleanExtra("adaptiveRecording", false); editor.putString("runningTrackFile", tf); editor.putFloat("runningPrecision", minimumPrecision); editor.putLong("runningDistanceChange", distanceChange); editor.putLong("runningUpdateTime", updateTime); editor.putLong("runningUpdateTimeFast", updateTimeFast); editor.putLong("runningSpeedLimit", speedLimit); editor.putBoolean("adaptiveRecording", adaptiveRecording); editor.commit(); } Intent cordovaMainIntent; try { PackageManager packageManager = this.getPackageManager(); cordovaMainIntent = packageManager.getLaunchIntentForPackage(this.getPackageName()); Log.d(LOG_TAG, "got cordovaMainIntent " + cordovaMainIntent); if (cordovaMainIntent == null) { throw new PackageManager.NameNotFoundException(); } } catch (PackageManager.NameNotFoundException e) { cordovaMainIntent = new Intent(); } PendingIntent pend = PendingIntent.getActivity(this, 0, cordovaMainIntent, 0); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ifString), 0); NotificationCompat.Action stop = new NotificationCompat.Action.Builder(android.R.drawable.ic_delete, "Stop recording", pendingIntent).build(); note = new NotificationCompat.Builder(this).setContentTitle(applicationName + " GPS tracking") .setSmallIcon(android.R.drawable.ic_menu_mylocation).setOngoing(true).setContentIntent(pend) .setContentText("No location yet."); note.addAction(stop); nm = (NotificationManager) getSystemService(Activity.NOTIFICATION_SERVICE); nm.notify(0, note.build()); recording = true; Log.d(LOG_TAG, "recording in handleIntent"); try { // create directory first, if it does not exist File trackFile = new File(tf).getParentFile(); if (!trackFile.exists()) { trackFile.mkdirs(); Log.d(LOG_TAG, "done creating path for trackfile: " + trackFile); } Log.d(LOG_TAG, "going to create RandomAccessFile " + tf); myWriter = new RandomAccessFile(tf, "rw"); if (intent != null) { // start new file // myWriter.setLength(0); // delete all contents from file String trackName = intent.getStringExtra("trackName"); String trackHead = initTrack(trackName).toString(); myWriter.write(trackHead.getBytes()); // we want to write JSON manually for streamed writing myWriter.seek(myWriter.length() - 1); myWriter.write(",\"coordinates\":[]}".getBytes()); } } catch (IOException e) { Log.d(LOG_TAG, "io error. cannot write to file " + tf); } locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, updateTime, distanceChange, mgpsll); if (locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER)) { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, updateTime, distanceChange, mnetll); } return START_STICKY; }
From source file:caesar.feng.framework.utils.ACache.java
/** * ? byte ?//w w w .ja v a 2 s. com * * @param key * @return byte ? */ public byte[] getAsBinary(String key) { RandomAccessFile RAFile = null; boolean removeFile = false; try { File file = mCache.get(key); if (!file.exists()) return null; RAFile = new RandomAccessFile(file, "r"); byte[] byteArray = new byte[(int) RAFile.length()]; RAFile.read(byteArray); if (!Utils.isDue(byteArray)) { return Utils.clearDateInfo(byteArray); } else { removeFile = true; return null; } } catch (Exception e) { e.printStackTrace(); return null; } finally { if (RAFile != null) { try { RAFile.close(); } catch (IOException e) { e.printStackTrace(); } } if (removeFile) remove(key); } }
From source file:com.slytechs.capture.file.editor.FileEditorImpl.java
/** * <p>/*from ww w. java2 s . c o m*/ * Flushes all the changes that currently exist in the "edits" buffer into a * temporary secondary file. After the copy the original file is removed and * the temporary file is renamed back to the original file which now contains * the contents of the "edits" buffer. * </p> * <p> * All the regions and their overlays are iterated over one segment at a time, * this includes the big segment consiting of the original file content, and * their reader's are asked to copy their buffers out to the temporary file's * channel in their individual smaller segments. * </p> * * @throws IOException * any IO errors with either the source file or the temporary file * operation's during the flush */ private void flushByCopy() throws IOException { /* * Create a temp file */ final File temp = File.createTempFile(this.file.getName(), null); final FileChannel tempChannel = new RandomAccessFile(temp, "rw").getChannel(); /* * Copy entire edits tree, including the root file, to temp file */ for (final RegionSegment<PartialLoader> segment : this.edits) { final PartialLoader loader = new ConstrainedPartialLoader(segment.getData(), segment); loader.transferTo(tempChannel); } this.channel.close(); tempChannel.close(); System.gc(); /* * We're done with the original file. All changes are now in the temp file * Try rename first, if it doesn't exist then do it by copy */ if (file.delete() == false) { throw new IOException("Unable to delete original file during flushByCopy()"); } if (temp.renameTo(file) == false) { throw new IOException("Unable to move temporary file during flushByCopy()"); } final String accessMode = (mode.isContent() ? "rw" : "r"); /* * Now we need to reopen the channel */ this.channel = new RandomAccessFile(file, accessMode).getChannel(); }
From source file:com.liferay.portal.util.FileImpl.java
public byte[] getBytes(File file) throws IOException { if ((file == null) || !file.exists()) { return null; }/*from ww w. ja v a2 s. c o m*/ RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); byte[] bytes = new byte[(int) randomAccessFile.length()]; randomAccessFile.readFully(bytes); randomAccessFile.close(); return bytes; }
From source file:dk.statsbiblioteket.util.LineReader.java
/** * Ensure that the {@link #channelIn} is ready for reading. * * @throws IOException if channelIn could not be opened. *//*from w ww. ja v a 2s .c o m*/ private void checkInputFile() throws IOException { if (inOpen) { return; } log.trace("Opening input channel for '" + file + "'"); // input = new FileInputStream(file); input = new RandomAccessFile(file, "r"); channelIn = input.getChannel(); seek(position); inOpen = true; }