List of usage examples for java.io RandomAccessFile RandomAccessFile
public RandomAccessFile(File file, String mode) throws FileNotFoundException
From source file:com.polyvi.xface.extension.advancedfiletransfer.XFileDownloader.java
@Override public void transfer(XCallbackContext callbackCtx) { initDownloadInfo();/* www .j a v a 2s.c o m*/ if (mState == DOWNLOADING) { return; } mCallbackCtx = callbackCtx; if (null == mDownloadInfo) { onError(CONNECTION_ERR); } else { setState(DOWNLOADING); new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; RandomAccessFile randomAccessFile = null; InputStream is = null; int retry = RETRY; //TODO:????? do { int completeSize = mDownloadInfo.getCompleteSize(); try { URL url = new URL(mUrl); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(TIME_OUT_MILLISECOND); connection.setRequestMethod("GET"); // ?Rangebytes x-; connection.setRequestProperty("Range", "bytes=" + completeSize + "-"); //cookie setCookieProperty(connection, mUrl); // ?.temp randomAccessFile = new RandomAccessFile(mLocalFilePath + TEMP_FILE_SUFFIX, "rwd"); randomAccessFile.seek(completeSize); // ??? is = connection.getInputStream(); byte[] buffer = new byte[mBufferSize]; int length = -1; while ((length = is.read(buffer)) != -1) { try { randomAccessFile.write(buffer, 0, length); } catch (Exception e) { retry = -1; break; } completeSize += length; onProgressUpdated(completeSize, 0); if (PAUSE == mState) { break; } } if (mDownloadInfo.isDownloadCompleted()) { // ??.temp renameFile(mLocalFilePath + TEMP_FILE_SUFFIX, mLocalFilePath); onSuccess(); break; } } catch (IOException e) { if (retry <= 0) { onError(CONNECTION_ERR); XLog.e(CLASS_NAME, e.getMessage()); } // ,?1? try { Thread.sleep(RETRY_INTERVAL); } catch (InterruptedException ex) { XLog.e(CLASS_NAME, "sleep be interrupted", ex); } } finally { try { if (null != is) { is.close(); } if (null != randomAccessFile) { // new URL??randomAccessFilenull randomAccessFile.close(); } if (null != connection) { // new URL??connectionnull connection.disconnect(); } } catch (IOException e) { XLog.e(CLASS_NAME, e.getMessage()); } } } while ((DOWNLOADING == mState) && (0 < retry--)); } }).start(); } }
From source file:hydrograph.ui.perspective.dialog.PreStartActivity.java
private boolean updateINIFile(String javaHome) { logger.debug("Updating JAVA_HOME in ini file ::" + javaHome); javaHome = "-vm\n" + javaHome + "\n"; RandomAccessFile file = null; boolean isUpdated = false; try {//from w w w . jav a 2 s . c o m file = new RandomAccessFile(new File(HYDROGRAPH_INI), "rw"); byte[] text = new byte[(int) file.length()]; file.readFully(text); file.seek(0); file.writeBytes(javaHome); file.write(text); isUpdated = true; } 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 updating " + HYDROGRAPH_INI + " file", ioException); } } return isUpdated; }
From source file:com.bristle.javalib.io.FileUtil.java
/************************************************************************** * Copy the contents of the specified binary file to the specified Writer. *@param strFilename Name of the file to copy. *@param writer Writer to write to. *@throws FileNotFoundException//from w w w . j ava 2 s . c o m * When binary file not found. *@throws IOException When an I/O error occurs reading the file or * writing it to the Writer. **************************************************************************/ public static void copyBinaryFileToWriter(String strFilename, Writer writer) throws FileNotFoundException, IOException { RandomAccessFile file = new RandomAccessFile(strFilename, "r"); try { int i; while (-1 != (i = file.read())) { writer.write((char) i); } writer.flush(); } finally { file.close(); } }
From source file:com.kkbox.toolkit.image.KKImageRequest.java
@Override public Bitmap doInBackground(Object... params) { Bitmap bitmap;//from www . j a va2 s. co m try { int readLength; cachePath = KKImageManager.getTempImagePath(context, url); File cacheFile = new File(cachePath); File localFile = null; String tempFilePath = context.getCacheDir().getAbsolutePath() + File.separator + "image" + File.separator + hashCode(); if (localPath != null) { localFile = new File(localPath); } try { if (cacheFile.exists()) { if (actionType == KKImageManager.ActionType.DOWNLOAD) { if (localFile == null || !localFile.exists()) { cryptToFile(cachePath, localPath); } return null; } else { bitmap = decodeBitmap(cachePath); if (bitmap != null) { if (localPath != null && saveToLocal && (localFile == null || !localFile.exists())) { cryptToFile(cachePath, localPath); } return bitmap; } else { removeCacheFile(); } } } if (localFile != null && localFile.exists()) { if (actionType == KKImageManager.ActionType.DOWNLOAD) { return null; } else { cryptToFile(localPath, tempFilePath); moveFileTo(tempFilePath, cachePath); bitmap = decodeBitmap(cachePath); if (bitmap != null) { return bitmap; } else { removeCacheFile(); } } } } catch (Exception e) { } // Do fetch server resource if either cache nor local file is not valid to read if (!KKImageManager.networkEnabled) { return null; } final HttpGet httpget = new HttpGet(url); response = httpclient.execute(httpget); final InputStream is = response.getEntity().getContent(); headers = response.getAllHeaders(); removeInvalidImageFiles(); if (actionType == KKImageManager.ActionType.DOWNLOAD) { RandomAccessFile tempFile = new RandomAccessFile(tempFilePath, "rw"); while ((readLength = is.read(buffer, 0, buffer.length)) != -1) { if (interuptFlag) { return null; } if (cipher != null) { buffer = cipher.doFinal(buffer); } tempFile.write(buffer, 0, readLength); } tempFile.close(); moveFileTo(tempFilePath, localPath); return null; } else { RandomAccessFile tempFile; try { tempFile = new RandomAccessFile(tempFilePath, "rw"); } catch (IOException e) { // we don't save to SD card if cache is full return BitmapFactory.decodeStream(is); } try { while ((readLength = is.read(buffer, 0, buffer.length)) != -1) { if (interuptFlag) { return null; } tempFile.write(buffer, 0, readLength); } } catch (IOException e) { tempFile.close(); return null; } tempFile.close(); moveFileTo(tempFilePath, cachePath); bitmap = decodeBitmap(cachePath); if (bitmap != null) { if (saveToLocal && localPath != null) { cryptToFile(cachePath, localPath); } return bitmap; } } } catch (final Exception e) { isNetworkError = true; removeInvalidImageFiles(); } return null; }
From source file:net.modsec.ms.connector.ConnRequestHandler.java
/** * Writes the modified modsecurity configurations to configuration file. * @param json contains modsecurity configurations as json object. *//*from w w w . j a v a 2s. c om*/ @SuppressWarnings("unchecked") public static void onWriteMSConfig(JSONObject json) { log.info("onWriteMSConfig called.. : " + json.toJSONString()); MSConfig serviceCfg = MSConfig.getInstance(); JSONObject jsonResp = new JSONObject(); String fileName = serviceCfg.getConfigMap().get("MSConfigFile"); String modifiedStr = ""; InputStream ins = null; FileOutputStream out = null; BufferedReader br = null; try { File file = new File(fileName); DataInputStream in; @SuppressWarnings("resource") FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); FileLock lock = channel.lock(); try { ins = new FileInputStream(file); in = new DataInputStream(ins); br = new BufferedReader(new InputStreamReader(in)); String line = ""; boolean check; while ((line = br.readLine()) != null) { check = true; //log.info("Line :" + line); for (ModSecConfigFields field : ModSecConfigFields.values()) { if (line.startsWith(field.toString())) { if (line.trim().split(" ")[0].equals(field.toString())) { if (json.containsKey(field.toString())) { if (((String) json.get(field.toString())).equals("") || json.get(field.toString()) == null) { log.info("---------- Log Empty value ----:" + (String) json.get(field.toString())); json.remove(field.toString()); check = false; continue; } else { modifiedStr += field.toString() + " " + json.remove(field.toString()) + "\n"; check = false; } } } } } if (check) { modifiedStr += line + "\n"; } } for (ModSecConfigFields field : ModSecConfigFields.values()) { if (json.containsKey(field.toString())) { if (json.get(field.toString()) == null || ((String) json.get(field.toString())).equals("")) { log.info("---------- Log Empty value ----:" + (String) json.get(field.toString())); json.remove(field.toString()); check = false; continue; } else { modifiedStr += field.toString() + " " + json.remove(field.toString()) + "\n"; } } } //modified string writing to modsecurity configurations log.info("Writing File :" + modifiedStr); out = new FileOutputStream(fileName); out.write(modifiedStr.getBytes()); log.info("ModSecurity Configurations configurations Written ... "); } finally { lock.release(); } br.close(); in.close(); ins.close(); out.close(); //For Restarting modsecurity so that modified configuration can be applied JSONObject restartJson = new JSONObject(); restartJson.put("action", "restart"); String cmd = serviceCfg.getConfigMap().get("MSRestart"); executeShScript(cmd, restartJson); jsonResp.put("action", "writeMSConfig"); jsonResp.put("status", "0"); jsonResp.put("message", "Configurations updated!"); } catch (FileNotFoundException e1) { jsonResp.put("action", "writeMSConfig"); jsonResp.put("status", "1"); jsonResp.put("message", "Internal Service is down!"); e1.printStackTrace(); } catch (IOException | NullPointerException e) { jsonResp.put("action", "writeMSConfig"); jsonResp.put("status", "0"); jsonResp.put("message", "Unable to modify configurations. Sorry of inconvenience"); e.printStackTrace(); } log.info("Sending Json :" + jsonResp.toJSONString()); ConnectorService.getConnectorProducer().send(jsonResp.toJSONString()); jsonResp.clear(); }
From source file:com.norconex.commons.lang.io.CachedOutputStream.java
@SuppressWarnings("resource") private void cacheToFile() throws IOException { fileCache = File.createTempFile("CachedOutputStream-", "-temp", cacheDirectory); fileCache.deleteOnExit();/*from w w w . ja v a2 s. co m*/ LOG.debug("Reached max cache size. Swapping to file: " + fileCache); RandomAccessFile f = new RandomAccessFile(fileCache, "rw"); FileChannel channel = f.getChannel(); fileOutputStream = Channels.newOutputStream(channel); IOUtils.write(memOutputStream.toByteArray(), fileOutputStream); memOutputStream = null; }
From source file:net.sf.ehcache.store.DiskStore.java
private void initialiseFiles() throws Exception { // Make sure the cache directory exists final File diskDir = new File(diskPath); if (diskDir.exists() && !diskDir.isDirectory()) { throw new Exception( "Store directory \"" + diskDir.getCanonicalPath() + "\" exists and is not a directory."); }//www . ja v a2s . c om if (!diskDir.exists() && !diskDir.mkdirs()) { throw new Exception("Could not create cache directory \"" + diskDir.getCanonicalPath() + "\"."); } dataFile = new File(diskDir, getDataFileName()); indexFile = new File(diskDir, getIndexFileName()); deleteIndexIfNoData(); if (persistent) { //if diskpath contains auto generated string if (diskPath.indexOf(AUTO_DISK_PATH_DIRECTORY_PREFIX) != -1) { LOG.warn( "Data in persistent disk stores is ignored for stores from automatically created directories" + " (they start with " + AUTO_DISK_PATH_DIRECTORY_PREFIX + ").\n" + "Remove diskPersistent or resolve the conflicting disk paths in cache configuration.\n" + "Deleting data file " + getDataFileName()); dataFile.delete(); } else if (!readIndex()) { if (LOG.isDebugEnabled()) { LOG.debug("Index file dirty or empty. Deleting data file " + getDataFileName()); } dataFile.delete(); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Deleting data file " + getDataFileName()); } dataFile.delete(); indexFile = null; } // Open the data file as random access. The dataFile is created if necessary. randomAccessFile = new RandomAccessFile(dataFile, "rw"); }
From source file:com.ibm.watson.developer_cloud.android.text_to_speech.v1.TTSUtility.java
private byte[] analyzeOpusData(InputStream is) { String inFilePath = getBaseDir() + "Watson.opus"; String outFilePath = getBaseDir() + "Watson.pcm"; File inFile = new File(inFilePath); File outFile = new File(outFilePath); outFile.deleteOnExit();//from w ww .j a v a 2 s . co m inFile.deleteOnExit(); try { RandomAccessFile inRaf = new RandomAccessFile(inFile, "rw"); byte[] opus = IOUtils.toByteArray(is); inRaf.write(opus); sampleRate = OggOpus.decode(inFilePath, outFilePath, sampleRate); // zero means to detect the sample rate by decoder RandomAccessFile outRaf = new RandomAccessFile(outFile, "r"); byte[] data = new byte[(int) outRaf.length()]; int outLength = outRaf.read(data); inRaf.close(); outRaf.close(); if (outLength == 0) { throw new IOException("Data reading failed"); } return data; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return new byte[0]; }
From source file:com.yobidrive.diskmap.needles.NeedleManager.java
private void initializeNeedleFiles() throws NeedleManagerException { // Browse directory for needle files (won't find any if rebuild required) String files[] = logDir.list(); if (files != null) { for (String file : files) { // Verifies file name pattern and extracts file number int extIndex = file.indexOf(EXTENSION); if (extIndex <= 0) continue; int fileNumber = -1; String hexString = file.substring(0, extIndex); try { fileNumber = Integer.parseInt(hexString, 16); } catch (Throwable th) { fileNumber = -1;/*from w w w.j a v a 2 s.c om*/ } if (fileNumber < 0) { // Normal situation: non log files (including the bucket file) continue; } if (fileNumber > logNumber) logNumber = fileNumber; File needleFile = new File(logDir, file); if (!needleFile.canRead() || !needleFile.canWrite()) { logger.error("No read/write access to " + logPath + "/" + file); throw new NeedleManagerException(); } RandomAccessFile needleRFile; try { needleRFile = new RandomAccessFile(needleFile, mode); // AutoCommit of content writes (rws), content + meta (rwd), or nothing (rw) } catch (Throwable th) { logger.error("File not found " + logPath + "/" + file); throw new NeedleManagerException(); } FileChannel needleChannel = needleRFile.getChannel(); channelMap.putIfAbsent(fileNumber, needleChannel); } } }
From source file:mediathekplugin.Database.java
public ArrayList<MediathekProgramItem> getMediathekPrograms(final Program program) { ArrayList<MediathekProgramItem> result = new ArrayList<MediathekProgramItem>(); String channelName = unifyChannelName(program.getChannel().getName()); HashMap<Long, ArrayList<Integer>> programsMap = mChannelItems.get(channelName); // search parts in brackets like for ARD if (programsMap == null && channelName.contains("(")) { String bracketPart = StringUtils.substringBetween(channelName, "(", ")"); programsMap = mChannelItems.get(bracketPart); }//from w w w. j a v a 2 s .c o m // search for partial name, if full name is not found if (programsMap == null && channelName.contains(" ")) { String firstPart = StringUtils.substringBefore(channelName, " "); programsMap = mChannelItems.get(firstPart); } if (programsMap == null) { for (Entry<String, HashMap<Long, ArrayList<Integer>>> entry : mChannelItems.entrySet()) { if (StringUtils.startsWithIgnoreCase(channelName, entry.getKey())) { programsMap = entry.getValue(); break; } } } if (programsMap == null) { return result; } String title = program.getTitle(); ArrayList<Integer> programs = programsMap.get(getKey(title)); if (programs == null && title.endsWith(")") && title.contains("(")) { String newTitle = StringUtils.substringBeforeLast(title, "(").trim(); programs = programsMap.get(getKey(newTitle)); } if (programs == null && title.endsWith("...")) { String newTitle = title.substring(0, title.length() - 3).trim(); programs = programsMap.get(getKey(newTitle)); } if (programs == null) { return result; } try { RandomAccessFile file = new RandomAccessFile(new File(mFileName), "r"); for (Integer byteOffset : programs) { file.seek(byteOffset); String lineEncoded = file.readLine(); String line = new String(lineEncoded.getBytes(), "UTF-8"); Matcher itemMatcher = ITEM_PATTERN.matcher(line); if (itemMatcher.find()) { String itemTitle = itemMatcher.group(3).trim(); String itemUrl = itemMatcher.group(4).trim(); result.add(new MediathekProgramItem(itemTitle, itemUrl, null)); } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; }