List of usage examples for java.io RandomAccessFile readFully
public final void readFully(byte b[]) throws IOException
From source file:org.gcaldaemon.core.Synchronizer.java
private final void loadEventRegistry() { if (!eventRegistry.isEmpty()) { return;/* w ww.j av a2 s . c om*/ } RandomAccessFile file = null; try { if (eventRegistryFile.isFile()) { // Load history file file = new RandomAccessFile(eventRegistryFile, "r"); int len = (int) eventRegistryFile.length(); byte[] bytes = new byte[len]; file.readFully(bytes); file.close(); String content = StringUtils.decodeToString(bytes, StringUtils.US_ASCII); bytes = null; // Parse history file StringTokenizer st = new StringTokenizer(content, "\r\n"); HashMap uids = new HashMap(); String urlHash = new String(); String line; int i; while (st.hasMoreTokens()) { line = st.nextToken().trim(); if (line.startsWith("URL\t")) { if (!uids.isEmpty()) { eventRegistry.put(urlHash, uids); } i = line.indexOf('\t'); if (i != -1) { urlHash = line.substring(i + 1); uids = new HashMap(); } continue; } i = line.indexOf('\t'); if (i != -1) { uids.put(line.substring(0, i), new Long(line.substring(i + 1))); } } if (!uids.isEmpty()) { eventRegistry.put(urlHash, uids); } if (log.isDebugEnabled()) { log.debug("Event registry loaded successfully (" + len + " bytes)."); } return; } } catch (Exception ioError) { if (file != null) { try { file.close(); eventRegistryFile.delete(); } catch (Exception ignored) { } } log.warn("Unable to load event registry!", ioError); } }
From source file:com.liferay.portal.util.FileImpl.java
public byte[] getBytes(File file) throws IOException { if ((file == null) || !file.exists()) { return null; }/*from w ww . jav a 2 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:org.mhisoft.wallet.service.AttachmentService.java
private byte[] _readFileContent(boolean decompress, final int storeVersion, String fileStoreDataFile, FileAccessEntry entry, PBEEncryptor encryptor) { try {/*from w w w. jav a 2 s. c o m*/ RandomAccessFile fileStore = new RandomAccessFile(fileStoreDataFile, "rw"); fileStore.seek(entry.getPosOfContent()); byte[] _encedBytes = new byte[entry.getEncSize()]; fileStore.readFully(_encedBytes); byte[] fileContent = encryptor.decrypt(_encedBytes, entry.getAlgorithmParameters()); //after decrypt, deflate the compressed data if (decompress && storeVersion >= WalletModel.LATEST_DATA_VERSION) { GZIPInputStream decompressedStream = new GZIPInputStream(new ByteArrayInputStream(fileContent)); fileContent = IOUtils.toByteArray(decompressedStream); } entry.setFileContent(fileContent); entry.setSize(fileContent.length); //decrypted size. fileStore.close(); return fileContent; } catch (IOException e) { e.printStackTrace(); DialogUtils.getInstance().error("Can't read " + fileStoreDataFile + ":" + e.toString()); } return null; }
From source file:org.andrewberman.sync.PDFDownloader.java
void retrievePDFsFromHTML() throws Exception { if (!baseDir.exists() || !baseDir.canWrite() || !baseDir.isDirectory()) { throw new Exception("Error: Destination is read-only or does not exist."); }//from ww w . j a va 2 s. c o m String base = baseDir.getCanonicalPath() + sep; syncBibTex(); do { Thread.sleep(InheritMe.BETWEEN_PDF_DOWNLOADS_SLEEP_TIME); getArticleInfo(); /* * First thing's first, create folders and insert the URL links if necessary. */ if (subTags) { status("Creating folders and links..."); createTagFoldersAndLinks(tagSet); status("Folders and links created!"); // Thread.sleep(PAUSE_TIME/10); } List<CiteULikeReference> articlesWithoutPDFs = this.getArticlesWithoutPDFs(this.refs); List<CiteULikeReference> articlesWithPDFs = new ArrayList<CiteULikeReference>(); articlesWithPDFs.addAll(this.refs); articlesWithPDFs.removeAll(articlesWithoutPDFs); itemMax = articlesWithPDFs.size(); itemNum = 0; int i = -1; for (CiteULikeReference ref : articlesWithPDFs) { System.out.println(ref.userfiles); itemNum++; i++; waitOrExit(); setArticleLink("Current article ID: " + ref.article_id, ref.href); try { waitOrExit(); // Grab the article page's text to get the date. Date remote = null; // if (this.uploadNewer) { String articleContent = get(ref.href); remote = getStampFromArticlePage(articleContent); System.out.println("Remote timestamp: " + remote); // } status("Checking for existing file..."); for (String fileName : ref.userfiles.keySet()) { waitOrExit(); String fullPath = ref.userfiles.get(fileName); System.out.println(fileName + " -> " + fullPath); /* * Try and put the year first. */ String[] bits = fileName.split("_"); String yearS = ""; String otherFilename = ""; String targetFilename = ""; if (bits.length == 3) { String flipped = bits[1] + "_" + bits[0] + "_" + bits[2]; if (flipFilename) { otherFilename = fileName; targetFilename = flipped; } else { targetFilename = fileName; otherFilename = flipped; } if (subYears) { yearS = String.valueOf(bits[1]); } } else { targetFilename = fileName; otherFilename = fileName; } /* * If we're organized by tags, add a destination file for each of this PDf's tags. * If not, then just add the one outputFile to the outputFiles array. */ ArrayList<File> outputFiles = new ArrayList<File>(); ArrayList<File> maybeNewFiles = new ArrayList<File>(); File altFile = null; File myFile = null; // Keep track of the newest file and its timestamp. File newestFile = null; long newestStamp = 0; if (subTags && ref.getTags().size() > 0) { for (String tag : ref.getTags()) { if (tag.equalsIgnoreCase("no-tag")) tag = ""; String curDir = base + tag + sep; curDir += yearS; myFile = new File(curDir + sep + targetFilename); altFile = new File(curDir + sep + otherFilename); if (myFile.exists()) { newestFile = returnNewer(newestFile, myFile); } else if (altFile.exists()) { try { altFile.renameTo(myFile); } catch (Exception e) { e.printStackTrace(); } // outputFiles.add(myFile); } else { outputFiles.add(myFile); } } } else { myFile = new File(base + yearS + sep + targetFilename); altFile = new File(base + yearS + sep + otherFilename); maybeNewFiles.add(myFile); maybeNewFiles.add(altFile); if (myFile.exists()) { newestFile = returnNewer(newestFile, myFile); } else if (altFile.exists()) { try { altFile.renameTo(myFile); } catch (Exception e) { e.printStackTrace(); System.exit(0); } // outputFiles.add(myFile); } else { outputFiles.add(myFile); } } // If we have a newest file, check against the server to see if it's much newer. if (newestFile != null && remote != null) { Date local = new Date(newestFile.lastModified()); long lT = local.getTime(); long rT = remote.getTime(); if (lT - rT > (1000) * (60) * (1)) // Fudge factor of 1 minute. { if (uploadNewer) { System.err.println("Local file is newer than remote! Uploading..."); status("Local file was modified! Uploading..."); // OK. Since CiteULike now uses hashing to evaluate the identity of files, we have to first delete // the existing attachment with this filename. String url = this.BASE_URL + "personal_pdf_delete?"; url += "username=" + this.username; url += "&article_id=" + ref.article_id; // Parse the userfile_id from the filename: String userFileId = ref.userfileIds.get(fileName); url += "&userfile_id=" + userFileId; System.out.println(url); get(url); uploadPDF(ref.article_id, newestFile); // Re-collect the timestamp, and re-stamp the local file. This is done so they match after re-uploading. String newContent = get(ref.href); Date remote2 = getStampFromArticlePage(newContent); newestFile.setLastModified(remote2.getTime()); } } } if (outputFiles.size() == 0) { status("Already up-to-date!"); utd++; continue; } Thread.sleep(200); /* * Download the PDF to the first file. */ waitOrExit(); status("Downloading..."); File f = outputFiles.remove(0); try { String fileUrl = this.BASE_URL + fullPath; this.retriesLeft = 2; downloadURLToFile(fileUrl, f); if (remote != null) f.setLastModified(remote.getTime()); } catch (Exception e) { e.printStackTrace(); f.delete(); throw e; } dl++; /* * Go through rest of tags, and copy file accordingly. * NOTE: This is only entered if this file needs to be copied over locally. */ for (int j = 0; j < outputFiles.size(); j++) { status("Copying PDF..."); File f2 = outputFiles.get(j); if (f2.exists()) { if (f2.lastModified() > newestStamp) { newestFile = f2; newestStamp = f2.lastModified(); } continue; } f2.getParentFile().mkdirs(); f2.createNewFile(); RandomAccessFile in = new RandomAccessFile(f, "r"); RandomAccessFile out = new RandomAccessFile(f2, "rw"); byte[] b = new byte[(int) in.length()]; in.readFully(b); out.write(b); in.close(); out.close(); f2.setLastModified(remote.getTime()); } } } catch (Exception e) { err++; e.printStackTrace(); status("Failed. See the Java console for more info."); Thread.sleep(PAUSE_TIME / 2); continue; } } } while (this.refs.size() > 0); this.pageNum = 0; status("Finished. " + dl + " new, " + utd + " up-to-date and " + err + " failed."); out.println("Done!"); }
From source file:hydrograph.ui.perspective.dialog.PreStartActivity.java
private boolean updateINIOnJDKUpgrade(String javaHome) { logger.debug("Updating INI file if JDK path is updated"); RandomAccessFile file = null; boolean isUpdated = false; try {/*from w w w .j a v a 2 s .c o m*/ file = new RandomAccessFile(new File(HYDROGRAPH_INI), "rw"); byte[] text = new byte[(int) file.length()]; while (file.getFilePointer() != file.length()) { if (StringUtils.equals(file.readLine(), "-vm")) { String currentLine = file.readLine(); if (StringUtils.equals(currentLine, javaHome)) { logger.debug("JAVA_HOME and -vm in configuration file are same"); } else { logger.debug( "JAVA_HOME and -vm in configuration file are different. Updating configuration file with JAVA_HOME"); file.seek(0); file.readFully(text); file.seek(0); updateData(text, javaHome, currentLine, file); isUpdated = true; } break; } } } catch (IOException ioException) { logger.error("IOException occurred while updating " + HYDROGRAPH_INI + " file", ioException); } finally { try { if (file != null) { file.close(); } } catch (IOException ioException) { logger.error("IOException occurred while closing " + HYDROGRAPH_INI + " file", ioException); } } return isUpdated; }
From source file:org.gcaldaemon.core.file.OnlineFileListener.java
private final Calendar loadEvent(File file) throws Exception { // MacOSX Leopard (one calendar = multiple iCal files) RandomAccessFile raf = null; for (int tries = 0;; tries++) { try {//from ww w. ja v a 2s. c o m if (log.isDebugEnabled()) { log.debug("Loading file " + file.getCanonicalPath().replace('\\', '/') + "..."); } raf = new RandomAccessFile(file, "r"); int len = (int) file.length(); byte[] bytes = new byte[len]; raf.readFully(bytes); raf.close(); if (log.isDebugEnabled()) { log.debug("File loaded successfully (" + len + " bytes)."); } return ICalUtilities.parseCalendar(bytes); } catch (Exception loadError) { if (raf != null) { try { raf.close(); } catch (Exception ignored) { } } if (tries == 5) { throw loadError; } Thread.sleep(500); } } }
From source file:com.qumasoft.qvcslib.CompareFilesWithApacheDiff.java
private CompareLineInfo[] buildLinesFromFile(File inFile) throws IOException { List<CompareLineInfo> lineInfoList = new ArrayList<>(); RandomAccessFile randomAccessFile = new RandomAccessFile(inFile, "r"); long fileLength = randomAccessFile.length(); int startOfLineSeekPosition = 0; int currentSeekPosition = 0; byte character; while (currentSeekPosition < fileLength) { character = randomAccessFile.readByte(); currentSeekPosition = (int) randomAccessFile.getFilePointer(); if (character == '\n') { int endOfLine = (int) randomAccessFile.getFilePointer(); byte[] buffer = new byte[endOfLine - startOfLineSeekPosition]; randomAccessFile.seek(startOfLineSeekPosition); randomAccessFile.readFully(buffer); String line = new String(buffer, UTF8); CompareLineInfo lineInfo = new CompareLineInfo(startOfLineSeekPosition, createCompareLine(line)); lineInfoList.add(lineInfo);/*from ww w . ja v a 2 s. c om*/ startOfLineSeekPosition = endOfLine; } } // Add the final line which can happen if it doesn't end in a newline. if ((fileLength - startOfLineSeekPosition) > 0L) { byte[] buffer = new byte[(int) fileLength - startOfLineSeekPosition]; randomAccessFile.seek(startOfLineSeekPosition); randomAccessFile.readFully(buffer); String line = new String(buffer, UTF8); CompareLineInfo lineInfo = new CompareLineInfo(startOfLineSeekPosition, createCompareLine(line)); lineInfoList.add(lineInfo); } CompareLineInfo[] lineInfoArray = new CompareLineInfo[lineInfoList.size()]; int i = 0; for (CompareLineInfo lineInfo : lineInfoList) { lineInfoArray[i++] = lineInfo; } return lineInfoArray; }
From source file:org.gcaldaemon.core.ldap.ContactLoader.java
public final synchronized GmailContact[] getContacts() { if (contacts == null) { try {/*from w ww . j a va 2s . c o m*/ // Network down - load contacts from vcards File file = new File(vcardDirectory, "contacts.csv"); if (!file.isFile()) { return new GmailContact[0]; } RandomAccessFile raf = new RandomAccessFile(file, "r"); byte[] bytes = new byte[(int) raf.length()]; raf.readFully(bytes); raf.close(); String csv = StringUtils.decodeToString(bytes, StringUtils.UTF_8); contacts = parseCSV(csv); log.debug(contacts.length + " contacts loaded successfully."); } catch (Exception ioError) { log.warn(ioError); } } return contacts; }
From source file:org.gcaldaemon.core.file.OnlineFileListener.java
protected final byte[] loadFile(int fileIndex) throws Exception { if (iCalFiles[fileIndex].isDirectory()) { // MacOSX Leopard (one calendar = multiple iCal files) return loadDir(fileIndex); }/*from w w w . j a v a 2s . c o m*/ // Standard iCal file (one calendar = one iCal file) RandomAccessFile raf = null; for (int tries = 0;; tries++) { try { if (log.isDebugEnabled()) { log.debug("Loading file " + iCalFiles[fileIndex].getCanonicalPath().replace('\\', '/') + "..."); } raf = new RandomAccessFile(iCalFiles[fileIndex], "r"); int len = (int) iCalFiles[fileIndex].length(); byte[] bytes = new byte[len]; raf.readFully(bytes); raf.close(); if (log.isDebugEnabled()) { log.debug("File loaded successfully (" + len + " bytes)."); } return bytes; } catch (Exception loadError) { if (raf != null) { try { raf.close(); } catch (Exception ignored) { } } if (tries == 5) { throw loadError; } Thread.sleep(500); } } }
From source file:com.siblinks.ws.service.impl.CommentServiceImpl.java
/** * {@inheritDoc}/* ww w .j a v a2 s . c o m*/ */ @Override @RequestMapping(value = "/getImageComment/{name}", method = RequestMethod.GET) public ResponseEntity<byte[]> getImageComment(@PathVariable(value = "name") final String name) { ResponseEntity<byte[]> responseEntity = null; RandomAccessFile randomAccessFile = null; try { if (name != null) { String directory = environment.getProperty("directoryImageComment"); String path = directory + "/" + name + ".png"; randomAccessFile = new RandomAccessFile(path, "r"); byte[] r = new byte[(int) randomAccessFile.length()]; randomAccessFile.readFully(r); responseEntity = new ResponseEntity<byte[]>(r, new HttpHeaders(), HttpStatus.OK); } else { responseEntity = new ResponseEntity<byte[]>(HttpStatus.NO_CONTENT); } } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); } finally { try { if (randomAccessFile != null) { randomAccessFile.close(); } } catch (IOException e) { // Do nothing } } return responseEntity; }