List of usage examples for java.io RandomAccessFile close
public void close() throws IOException
From source file:org.cloudata.core.commitlog.CommitLogServer.java
public String rollback(String dirName, String position) { LOG.debug("rollback is called! with dirName : " + dirName); RandomAccessFile file = null; try {/*from www . j a v a 2s . c om*/ File logFile = new File(commitLogStoreFile, CommitLogFileChannel.getLogFileName(dirName, Constants.PIPE_CL_FILE_NAME + listener.port)); file = new RandomAccessFile(logFile, "rws"); file.getChannel().truncate(Long.parseLong(position)); } catch (IOException e) { LOG.warn("rollbacking file is fail dir [" + dirName + "], pos : " + position, e); return "ABORT"; } finally { if (file != null) { try { file.close(); } catch (IOException e) { } } } return "OK"; }
From source file:com.koda.integ.hbase.storage.FileExtStorage.java
@Override public void close() throws IOException { LOG.info("Closing storage {" + fileStorageBaseDir + "} ..."); LOG.info("Stopping file flusher thread ..."); try {//from w w w . j a va2 s . c o m if (flusher != null) { while (flusher.isAlive()) { try { flusher.interrupt(); flusher.join(10000); } catch (InterruptedException e) { } } } LOG.info("Flusher stopped."); // Flush internal buffer flush(); writeLock.writeLock().lock(); LOG.info("Closing open files ..."); // Close all open files int count = 0; for (Queue<RandomAccessFile> files : readers.values()) { for (RandomAccessFile f : files) { try { count++; f.close(); } catch (Throwable t) { } } files.clear(); } readers.clear(); if (currentForWrite != null) { currentForWrite.close(); } LOG.info("Closing open files ... Done {" + count + "} files."); } finally { writeLock.writeLock().unlock(); } LOG.info("Closing storage {" + fileStorageBaseDir + "} ... Done."); }
From source file:com.l2jfree.gameserver.cache.CrestCache.java
public synchronized void reload() { FileFilter filter = new BmpFilter(); File dir = new File(Config.DATAPACK_ROOT, "data/crests/"); File[] files = dir.listFiles(filter); if (files == null) files = new File[0]; byte[] content; _loadedFiles = 0;//w w w .j a va2s .c om _bytesBuffLen = 0; _cachePledge.clear(); _cachePledgeLarge.clear(); _cacheAlly.clear(); for (File file : files) { RandomAccessFile f = null; try { f = new RandomAccessFile(file, "r"); content = new byte[(int) f.length()]; f.readFully(content); if (file.getName().startsWith("Crest_Large_")) { _cachePledgeLarge.put( Integer.valueOf(file.getName().substring(12, file.getName().length() - 4)), content); } else if (file.getName().startsWith("Crest_")) { _cachePledge.put(Integer.valueOf(file.getName().substring(6, file.getName().length() - 4)), content); } else if (file.getName().startsWith("AllyCrest_")) { _cacheAlly.put(Integer.valueOf(file.getName().substring(10, file.getName().length() - 4)), content); } _loadedFiles++; _bytesBuffLen += content.length; } catch (Exception e) { _log.warn("Problem with loading crest bmp file: " + file, e); } finally { try { if (f != null) f.close(); } catch (Exception e) { e.printStackTrace(); } } } _log.info(this); }
From source file:adept.io.Reader.java
/** * Reads specified file into a byte array. * * @param path the path//from w w w .j a va2s .c o m * @return the byte[] */ public byte[] readFileIntoByteArray(String path) { try { RandomAccessFile f = new RandomAccessFile(path, "r"); byte[] b = new byte[(int) f.length()]; f.read(b); f.close(); return b; } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:com.redhat.rhn.frontend.action.common.DownloadFile.java
@Override protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String path = ""; Map params = (Map) request.getAttribute(PARAMS); String type = (String) params.get(TYPE); if (type.equals(DownloadManager.DOWNLOAD_TYPE_KICKSTART)) { return getStreamInfoKickstart(mapping, form, request, response, path); } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_COBBLER)) { String url = ConfigDefaults.get().getCobblerServerUrl() + (String) params.get(URL_STRING); KickstartHelper helper = new KickstartHelper(request); String data = ""; if (helper.isProxyRequest()) { data = KickstartManager.getInstance().renderKickstart(helper.getKickstartHost(), url); } else {/*ww w . j ava2 s . c o m*/ data = KickstartManager.getInstance().renderKickstart(url); } setTextContentInfo(response, data.length()); return getStreamForText(data.getBytes()); } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_COBBLER_API)) { // read data from POST body String postData = new String(); String line = null; BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { postData += line; } // Send data URL url = new URL(ConfigDefaults.get().getCobblerServerUrl() + "/cobbler_api"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); // this will write POST /download//cobbler_api instead of // POST /cobbler_api, but cobbler do not mind wr.write(postData, 0, postData.length()); wr.flush(); conn.connect(); // Get the response String output = new String(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = rd.readLine()) != null) { output += line; } wr.close(); KickstartHelper helper = new KickstartHelper(request); if (helper.isProxyRequest()) { // Search/replacing all instances of cobbler host with host // we pass in, for use with Spacewalk Proxy. output = output.replaceAll(ConfigDefaults.get().getCobblerHost(), helper.getForwardedHost()); } setXmlContentInfo(response, output.length()); return getStreamForXml(output.getBytes()); } else { Long fileId = (Long) params.get(FILEID); Long userid = (Long) params.get(USERID); User user = UserFactory.lookupById(userid); if (type.equals(DownloadManager.DOWNLOAD_TYPE_PACKAGE)) { Package pack = PackageFactory.lookupByIdAndOrg(fileId, user.getOrg()); setBinaryContentInfo(response, pack.getPackageSize().intValue()); path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + pack.getPath(); return getStreamForBinary(path); } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_SOURCE)) { Package pack = PackageFactory.lookupByIdAndOrg(fileId, user.getOrg()); List<PackageSource> src = PackageFactory.lookupPackageSources(pack); if (!src.isEmpty()) { setBinaryContentInfo(response, src.get(0).getPackageSize().intValue()); path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + src.get(0).getPath(); return getStreamForBinary(path); } } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_REPO_LOG)) { Channel c = ChannelFactory.lookupById(fileId); ChannelManager.verifyChannelAdmin(user, fileId); StringBuilder output = new StringBuilder(); for (String fileName : ChannelManager.getLatestSyncLogFiles(c)) { RandomAccessFile file = new RandomAccessFile(fileName, "r"); long fileLength = file.length(); if (fileLength > DOWNLOAD_REPO_LOG_LENGTH) { file.seek(fileLength - DOWNLOAD_REPO_LOG_LENGTH); // throw away text till end of the actual line file.readLine(); } else { file.seek(0); } String line; while ((line = file.readLine()) != null) { output.append(line); output.append("\n"); } file.close(); if (output.length() > DOWNLOAD_REPO_LOG_MIN_LENGTH) { break; } } setTextContentInfo(response, output.length()); return getStreamForText(output.toString().getBytes()); } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_CRASHFILE)) { CrashFile crashFile = CrashManager.lookupCrashFileByUserAndId(user, fileId); String crashPath = crashFile.getCrash().getStoragePath(); setBinaryContentInfo(response, (int) crashFile.getFilesize()); path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + crashPath + "/" + crashFile.getFilename(); return getStreamForBinary(path); } } throw new UnknownDownloadTypeException( "The specified download type " + type + " is not currently supported"); }
From source file:com.csipsimple.service.DownloadLibService.java
private void dumpFile(HttpEntity entity, File partialDestinationFile, File destinationFile) throws IOException { if (!cancellingDownload) { totalSize = (int) entity.getContentLength(); if (totalSize <= 0) { totalSize = 1024;//from www . j a v a 2 s .c o m } byte[] buff = new byte[64 * 1024]; int read = 0; RandomAccessFile out = new RandomAccessFile(partialDestinationFile, "rw"); out.seek(0); InputStream is = entity.getContent(); TimerTask progressUpdateTimerTask = new TimerTask() { @Override public void run() { onProgressUpdate(); } }; Timer progressUpdateTimer = new Timer(); try { // If File exists, set the Progress to it. Otherwise it will be // initial 0 downloadedSize = 0; progressUpdateTimer.scheduleAtFixedRate(progressUpdateTimerTask, 100, 100); while ((read = is.read(buff)) > 0 && !cancellingDownload) { out.write(buff, 0, read); downloadedSize += read; } out.close(); is.close(); if (!cancellingDownload) { partialDestinationFile.renameTo(destinationFile); } } catch (IOException e) { out.close(); try { destinationFile.delete(); } catch (SecurityException ex) { Log.e(THIS_FILE, "Unable to delete downloaded File. Continue anyway.", ex); } } finally { progressUpdateTimer.cancel(); buff = null; } } }
From source file:com.roamprocess1.roaming4world.ui.messages.MessageAdapter.java
public boolean resumeImages(String msgSubject) { File file = null;/*from w w w. j a v a2s.com*/ long fileLength; try { String filename = "", num = ""; URL url = new URL(imageUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); num = getNumber(msgSubject); filename = getTimestamp(msgSubject); file = new File(fileDir + "/" + getNumber(msgSubject) + "/Recieved", filename); if (!file.exists()) { file.createNewFile(); } FileOutputStream fileOutput = new FileOutputStream(file); InputStream inputStream = connection.getInputStream(); int totalSize = connection.getContentLength(); Long downloadedSize = (long) 0; byte[] buffer = new byte[1024]; int bufferLength = 0; while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, bufferLength); downloadedSize += bufferLength; Log.i("Progress:", "downloadedSize:" + downloadedSize + "totalSize:" + totalSize); } fileOutput.close(); Log.d("downloadedSize", downloadedSize + " @"); if (downloadedSize == totalSize) { downloadedimageuri = file.getAbsolutePath(); return true; } if (file.exists()) { connection.setAllowUserInteraction(true); connection.setRequestProperty("Range", "bytes=" + file.length() + "-"); } connection.setConnectTimeout(14000); connection.setReadTimeout(20000); connection.connect(); if (connection.getResponseCode() / 100 != 2) throw new Exception("Invalid response code!"); else { String connectionField = connection.getHeaderField("content-range"); if (connectionField != null) { String[] connectionRanges = connectionField.substring("bytes=".length()).split("-"); downloadedSize = Long.valueOf(connectionRanges[0]); } if (connectionField == null && file.exists()) file.delete(); fileLength = connection.getContentLength() + downloadedSize; BufferedInputStream input = new BufferedInputStream(connection.getInputStream()); RandomAccessFile output = new RandomAccessFile(file, "rw"); output.seek(downloadedSize); byte data[] = new byte[1024]; int count = 0; int __progress = 0; while ((count = input.read(data, 0, 1024)) != -1 && __progress != 100) { downloadedSize += count; output.write(data, 0, count); __progress = (int) ((downloadedSize * 100) / fileLength); } output.close(); input.close(); } } catch (Exception e) { e.printStackTrace(); return false; } return false; }
From source file:com.baidubce.services.bos.BosClientTest.java
private static File createFile(String fileName, long length) throws IOException { File file = new File(fileName); RandomAccessFile r = null; try {//from www . ja v a2 s .c o m r = new RandomAccessFile(file, "rw"); r.setLength(length); } finally { if (r != null) { try { r.close(); } catch (IOException e) { e.printStackTrace(); } } } return file; }
From source file:no.sesat.search.http.filters.SiteJspLoaderFilter.java
private void downloadJsp(final HttpServletRequest request, final String jsp) throws MalformedURLException { final StopWatch stopWatch = new StopWatch(); stopWatch.start();// w ww . j av a2s .c o m byte[] golden = new byte[0]; // search skins for the jsp and write it out to "golden" for (Site site = (Site) request.getAttribute(Site.NAME_KEY); 0 == golden.length; site = site.getParent()) { if (null == site) { if (null == config.getServletContext().getResource(jsp)) { throw new ResourceLoadException("Unable to find " + jsp + " in any skin"); } break; } final Site finalSite = site; final BytecodeLoader bcLoader = UrlResourceLoader.newBytecodeLoader(finalSite.getSiteContext(), jsp, null); bcLoader.abut(); golden = bcLoader.getBytecode(); } // if golden now contains data save it to a local (ie local web application) file if (0 < golden.length) { try { final File file = new File(root + jsp); // create the directory structure file.getParentFile().mkdirs(); // check existing file boolean needsUpdating = true; final boolean fileExisted = file.exists(); if (!fileExisted) { file.createNewFile(); } // channel.lock() only synchronises file access between programs, but not between threads inside // the current JVM. The latter results in the OverlappingFileLockException. // At least this is my current understanding of java.nio.channels // It may be that no synchronisation or locking is required at all. A beer to whom answers :-) // So we must provide synchronisation between our own threads, // synchronisation against the file's path (using the JVM's String.intern() functionality) // should work. (I can't imagine this string be used for any other synchronisation purposes). synchronized (file.toString().intern()) { RandomAccessFile fileAccess = null; FileChannel channel = null; try { fileAccess = new RandomAccessFile(file, "rws"); channel = fileAccess.getChannel(); channel.lock(); if (fileExisted) { final byte[] bytes = new byte[(int) channel.size()]; final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); int reads; do { reads = channel.read(byteBuffer); } while (0 < reads); needsUpdating = !Arrays.equals(golden, bytes); } if (needsUpdating) { // download file from skin channel.write(ByteBuffer.wrap(golden), 0); file.deleteOnExit(); } } finally { if (null != channel) { channel.close(); } if (null != fileAccess) { fileAccess.close(); } LOG.debug("resource created as " + config.getServletContext().getResource(jsp)); } } } catch (IOException ex) { LOG.error(ex.getMessage(), ex); } } stopWatch.stop(); LOG.trace("SiteJspLoaderFilter.downloadJsp(..) took " + stopWatch); }
From source file:caesar.feng.framework.utils.ACache.java
/** * ? byte ?//ww w .j ava2 s . co m * * @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); } }