List of usage examples for java.io RandomAccessFile RandomAccessFile
public RandomAccessFile(File file, String mode) throws FileNotFoundException
From source file:edu.mbl.jif.imaging.mmtiff.MultipageTiffWriter.java
public MultipageTiffWriter(String directory, String filename, JSONObject summaryMD, TaggedImageStorageMultipageTiff mpTiffStorage) { masterMPTiffStorage_ = mpTiffStorage; omeTiff_ = mpTiffStorage.omeTiff_;/* w w w.ja v a 2 s . c o m*/ reader_ = new MultipageTiffReader(summaryMD); File f = new File(directory + "/" + filename); try { processSummaryMD(summaryMD); } catch (MMScriptException ex1) { ReportingUtils.logError(ex1); } catch (JSONException ex) { ReportingUtils.logError(ex); } //This is an overestimate of file size because file gets truncated at end long fileSize = Math.min(MAX_FILE_SIZE, summaryMD.toString().length() + 2000000 + numFrames_ * numChannels_ * numSlices_ * ((long) bytesPerImagePixels_ + 2000)); try { f.createNewFile(); raFile_ = new RandomAccessFile(f, "rw"); try { raFile_.setLength(fileSize); } catch (IOException e) { new Thread(new Runnable() { public void run() { try { Thread.sleep(1000); } catch (InterruptedException ex) { } //MMStudioMainFrame.getInstance().getAcquisitionEngine().abortRequest(); } }).start(); ReportingUtils.showError("Insufficent space on disk: no room to write data"); } fileChannel_ = raFile_.getChannel(); indexMap_ = new HashMap<String, Long>(); reader_.setFileChannel(fileChannel_); reader_.setIndexMap(indexMap_); buffers_ = new LinkedList<ByteBuffer>(); writeMMHeaderAndSummaryMD(summaryMD); } catch (IOException ex) { ReportingUtils.logError(ex); } try { summaryMDString_ = summaryMD.toString(2); } catch (JSONException ex) { summaryMDString_ = ""; } }
From source file:com.example.android.vault.EncryptedDocument.java
/** * Decrypt and read content section of this document, writing it into the * given pipe./*from ww w .j a v a2 s . c om*/ * <p/> * Pipe is left open, so caller is responsible for calling * {@link ParcelFileDescriptor#close()} or * {@link ParcelFileDescriptor#closeWithError(String)}. * * @param contentOut write end of a pipe. * @throws DigestException if content fails MAC check. Some or all content * may have already been written to the pipe when the MAC is * validated. */ public void readContent(ParcelFileDescriptor contentOut) throws IOException, GeneralSecurityException { final RandomAccessFile f = new RandomAccessFile(mFile, "r"); try { assertMagic(f); if (f.length() <= CONTENT_OFFSET) { throw new IOException("Document has no content"); } // Skip over metadata section f.seek(CONTENT_OFFSET); readSection(f, new FileOutputStream(contentOut.getFileDescriptor())); } finally { f.close(); } }
From source file:com.thinkberg.moxo.vfs.s3.jets3t.Jets3tFileObject.java
private FileChannel getCacheFileChannel() throws IOException { if (cacheFile == null) { cacheFile = File.createTempFile("moxo.", ".s3"); }/*from w w w. j a v a 2s . co m*/ return new RandomAccessFile(cacheFile, "rw").getChannel(); }
From source file:hudson.util.TextFile.java
/** * Efficiently reads the last N characters (or shorter, if the whole file is shorter than that.) * * <p>// w w w.jav a2 s .co m * This method first tries to just read the tail section of the file to get the necessary chars. * To handle multi-byte variable length encoding (such as UTF-8), we read a larger than * necessary chunk. * * <p> * Some multi-byte encoding, such as Shift-JIS (http://en.wikipedia.org/wiki/Shift_JIS) doesn't * allow the first byte and the second byte of a single char to be unambiguously identified, * so it is possible that we end up decoding incorrectly if we start reading in the middle of a multi-byte * character. All the CJK multi-byte encodings that I know of are self-correcting; as they are ASCII-compatible, * any ASCII characters or control characters will bring the decoding back in sync, so the worst * case we just have some garbage in the beginning that needs to be discarded. To accommodate this, * we read additional 1024 bytes. * * <p> * Other encodings, such as UTF-8, are better in that the character boundary is unambiguous, * so there can be at most one garbage char. For dealing with UTF-16 and UTF-32, we read at * 4 bytes boundary (all the constants and multipliers are multiples of 4.) * * <p> * Note that it is possible to construct a contrived input that fools this algorithm, and in this method * we are willing to live with a small possibility of that to avoid reading the whole text. In practice, * such an input is very unlikely. * * <p> * So all in all, this algorithm should work decently, and it works quite efficiently on a large text. */ public @Nonnull String fastTail(int numChars, Charset cs) throws IOException { RandomAccessFile raf = new RandomAccessFile(file, "r"); try { long len = raf.length(); // err on the safe side and assume each char occupies 4 bytes // additional 1024 byte margin is to bring us back in sync in case we started reading from non-char boundary. long pos = Math.max(0, len - (numChars * 4 + 1024)); raf.seek(pos); byte[] tail = new byte[(int) (len - pos)]; raf.readFully(tail); String tails = cs.decode(java.nio.ByteBuffer.wrap(tail)).toString(); return new String(tails.substring(Math.max(0, tails.length() - numChars))); // trim the baggage of substring by allocating a new String } finally { raf.close(); } }
From source file:com.parse.ParseKeyValueCache.java
static String loadFromKeyValueCache(final String key, final long maxAgeMilliseconds) { synchronized (MUTEX_IO) { File file = getKeyValueCacheFile(key); if (file == null) { return null; }/*from w ww .j a v a2 s . co m*/ Date now = new Date(); long oldestAcceptableAge = Math.max(0, now.getTime() - maxAgeMilliseconds); if (getKeyValueCacheAge(file) < oldestAcceptableAge) { return null; } // Update mtime to make the LRU work file.setLastModified(now.getTime()); try { RandomAccessFile f = new RandomAccessFile(file, "r"); byte[] bytes = new byte[(int) f.length()]; f.readFully(bytes); f.close(); return new String(bytes, "UTF-8"); } catch (IOException e) { PLog.e(TAG, "error reading from cache", e); return null; } } }
From source file:biz.neustar.nexus.plugins.gitlab.GitlabAuthenticatingRealmIT.java
License:asdf
@Override protected NexusBundleConfiguration configureNexus(final NexusBundleConfiguration configuration) { try {//from ww w . j a v a 2 s. c om // request 1 - good server.enqueue(new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .setBody(loadBody("good_user.json"))); // request 2 - bad, no user found server.enqueue(new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .setResponseCode(404).setStatus("Not Found")); // request 3 - bad, auth failed against gitlab server.enqueue(new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .setResponseCode(401).setStatus("Unauthorized")); server.play(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } System.out.println("MOCK SERVER: " + server.getHostName() + " " + server.getPort()); // override the format of the nexus.log file configuration.setLogPattern("%d{HH:mm:ss.SSS} %-5level - %msg%n"); // configure logging level of example plugins running in nexus configuration.setLogLevel("DEBUG"); configuration.setStartTimeout(120); Model model = getPomInfo(); String pluginName = model.getArtifactId() + "-" + model.getVersion(); File plugin = new File("target/" + pluginName + "-bundle.zip"); assertTrue(plugin.exists()); configuration.addPlugins(plugin); // why does this work in the examples.. pom is missing for me.. /* configuration.addPlugins( artifactResolver() .resolveFromDependencyManagement("biz.neustar.nexus", "nexus-gitlab-token-auth-plugin", "nexus-plugin", (String)null, "zip", "bundle") //.resolvePluginFromDependencyManagement("biz.neustar.nexus", "nexus-gitlab-token-auth-plugin") ); */ File tempPluginConfig = testData().resolveFile("gitlab-plugin-temp.xml"); // from the mock server try (RandomAccessFile tempConfig = new RandomAccessFile(tempPluginConfig, "r"); RandomAccessFile gitlabConfig = new RandomAccessFile( tempPluginConfig.getParent() + "/gitlab-plugin.xml", "rw");) { gitlabConfig.setLength(0); // truncate. String line = tempConfig.readLine(); while (line != null) { // GITLAB_URL gitlabConfig .write(line.replace("GITLAB_URL", "http://" + server.getHostName() + ":" + server.getPort()) .getBytes(UTF_8)); gitlabConfig.write('\n'); line = tempConfig.readLine(); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } // <realm>NexusGitlabAuthenticationRealm</realm> configuration.addOverlays( overlays.copy().file(file(testData().resolveFile("gitlab-plugin.xml"))).to() .directory(path("sonatype-work/nexus/conf")), overlays.copy().file(file(testData().resolveFile("security-configuration.xml"))).to() .directory(path("sonatype-work/nexus/conf"))); return configuration; }
From source file:jp.andeb.obbutil.ObbUtilMain.java
private static boolean doRemove(String[] args) { if (args.length != 1) { printUsage(PROGNAME);//www. ja va2s . co m return false; } final File targetFile = new File(args[0]); final RandomAccessFile targetRaFile; try { targetRaFile = new RandomAccessFile(targetFile, "rw"); } catch (FileNotFoundException e) { System.err.println("????: " + targetFile.getPath()); return false; } try { final ObbInfoV1 obbInfo; try { obbInfo = ObbInfoV1.fromFile(targetRaFile); } catch (IOException e) { System.err .println("????????: " + targetFile.getPath()); return false; } catch (NotObbException e) { System.err.println( "? OBB ???????: " + targetFile.getPath()); return false; } final ByteBuffer obbInfoBytes = obbInfo.toBytes(); targetRaFile.setLength(targetRaFile.length() - obbInfoBytes.remaining()); } catch (IOException e) { System.err.println("OBB ??????: " + targetFile.getPath()); return false; } finally { try { targetRaFile.close(); } catch (IOException e) { System.err.println("OBB ??????: " + targetFile.getPath()); return false; } } System.err.println("OBB ???????: " + targetFile.getPath()); return true; }
From source file:com.qubole.rubix.core.TestCachingInputStream.java
private void writeZeros(String filename, int start, int end) throws IOException { File file = new File(filename); RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(start);//from w w w.ja v a2 s . c o m String s = "0"; StandardCharsets.UTF_8.encode(s); for (int i = 0; i < (end - start); i++) { raf.writeBytes(s); } raf.close(); }
From source file:au.org.ala.spatial.util.RecordsSmall.java
private void makeUniquePoints() throws Exception { //make unique points and index points = new RandomAccessFile(filename + "records.csv.small.points", "r"); double[] allPoints = getPointsAll(); Coord[] p = new Coord[allPoints.length / 2]; for (int i = 0; i < allPoints.length; i += 2) { p[i / 2] = new Coord(allPoints[i], allPoints[i + 1], i / 2); }//from ww w.ja v a 2s. co m allPoints = null; //make available to GC Arrays.sort(p, new Comparator<Coord>() { public int compare(Coord o1, Coord o2) { return o1.longitude == o2.longitude ? (o1.latitude == o2.latitude ? 0 : (o1.latitude - o2.latitude > 0.0 ? 1 : -1)) : (o1.longitude - o2.longitude > 0.0 ? 1 : -1); } }); DataOutputStream outputUniquePoints = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(filename + "records.csv.small.pointsUniquePoints"))); DataOutputStream outputUniqueIdx = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(filename + "records.csv.small.pointsUniqueIdx"))); int pos = -1; //first point is set after pos++ int[] newPos = new int[p.length]; for (int i = 0; i < p.length; i++) { if (i == 0 || p[i].latitude != p[i - 1].latitude || p[i].longitude != p[i - 1].longitude) { outputUniquePoints.writeDouble(p[i].latitude); outputUniquePoints.writeDouble(p[i].longitude); pos++; } newPos[p[i].pos] = pos; } for (int i = 0; i < p.length; i++) { outputUniqueIdx.writeInt(newPos[i]); } outputUniqueIdx.flush(); outputUniqueIdx.close(); outputUniquePoints.flush(); outputUniquePoints.close(); points.close(); }
From source file:de.knowwe.visualization.util.Utils.java
private static boolean isFileClosedWindows(File file) { boolean closed; FileChannel channel = null;/* w ww .j ava 2s . co m*/ try { channel = new RandomAccessFile(file, "rw").getChannel(); closed = true; } catch (Exception ex) { closed = false; } finally { if (channel != null) { try { channel.close(); } catch (IOException ex) { // exception handling } } } return closed; }