List of usage examples for java.io RandomAccessFile close
public void close() throws IOException
From source file:com.emc.vipr.sync.source.FilesystemSource.java
protected void delete(File file) { // Try to lock the file first. If this fails, the file is // probably open for write somewhere. // Note that on a mac, you can apparently delete files that // someone else has open for writing, and can lock files // too.//from w w w . j a va 2 s.c om // Must make sure to throw exceptions when necessary to flag actual failures as opposed to skipped files. if (file.isDirectory()) { File metaDir = getMetaFile(file).getParentFile(); if (metaDir.exists()) metaDir.delete(); // Just try and delete dir if (!file.delete()) { LogMF.warn(l4j, "Failed to delete directory {0}", file); } } else { boolean tryDelete = true; if (deleteOlderThan > 0) { if (System.currentTimeMillis() - file.lastModified() < deleteOlderThan) { LogMF.info(l4j, "not deleting {0}; it is not at least {1} ms old", file, deleteOlderThan); tryDelete = false; } } if (deleteCheckScript != null) { String[] args = new String[] { deleteCheckScript.getAbsolutePath(), file.getAbsolutePath() }; try { l4j.debug("delete check: " + Arrays.asList(args)); Process p = Runtime.getRuntime().exec(args); while (true) { try { int exitCode = p.exitValue(); if (exitCode == 0) { LogMF.debug(l4j, "delete check OK, exit code {0}", exitCode); } else { LogMF.info(l4j, "delete check failed, exit code {0}. Not deleting file.", exitCode); tryDelete = false; } break; } catch (IllegalThreadStateException e) { // Ignore. } } } catch (IOException e) { LogMF.info(l4j, "error executing delete check script: {0}. Not deleting file.", e.toString()); tryDelete = false; } } RandomAccessFile raf = null; if (tryDelete) { try { raf = new RandomAccessFile(file, "rw"); FileChannel fc = raf.getChannel(); FileLock flock = fc.lock(); // If we got here, we should be good. flock.release(); if (!file.delete()) { throw new RuntimeException(MessageFormat.format("Failed to delete {0}", file)); } } catch (IOException e) { throw new RuntimeException(MessageFormat .format("File {0} not deleted, it appears to be open: {1}", file, e.getMessage())); } finally { if (raf != null) { try { raf.close(); } catch (IOException e) { // Ignore. } } } } } }
From source file:org.openmeetings.servlet.outputhandler.ExportToImage.java
@Override protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { try {/*from w w w. j av a 2 s.c o m*/ if (getUserManagement() == null || getSessionManagement() == null || getGenerateImage() == null) { return; } String sid = httpServletRequest.getParameter("sid"); if (sid == null) { sid = "default"; } log.debug("sid: " + sid); String hash = httpServletRequest.getParameter("hash"); if (hash == null) { hash = ""; } log.debug("hash: " + hash); String fileName = httpServletRequest.getParameter("fileName"); if (fileName == null) { fileName = "file_xyz"; } String exportType = httpServletRequest.getParameter("exportType"); if (exportType == null) { exportType = "svg"; } Long users_id = getSessionManagement().checkSession(sid); Long user_level = getUserManagement().getUserLevelByID(users_id); log.debug("users_id: " + users_id); log.debug("user_level: " + user_level); if (user_level != null && user_level > 0 && hash != "") { PrintBean pBean = PrintService.getPrintItemByHash(hash); // Whiteboard Objects @SuppressWarnings("rawtypes") List whiteBoardMap = pBean.getMap(); // Get a DOMImplementation. DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); // Create an instance of org.w3c.dom.Document. // String svgNS = "http://www.w3.org/2000/svg"; String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI; Document document = domImpl.createDocument(svgNS, "svg", null); // Get the root element (the 'svg' element). Element svgRoot = document.getDocumentElement(); // Set the width and height attributes on the root 'svg' // element. svgRoot.setAttributeNS(null, "width", "" + pBean.getWidth()); svgRoot.setAttributeNS(null, "height", "" + pBean.getHeight()); log.debug("pBean.getWidth(),pBean.getHeight()" + pBean.getWidth() + "," + pBean.getHeight()); // Create an instance of the SVG Generator. SVGGraphics2D svgGenerator = new SVGGraphics2D(document); svgGenerator = WhiteboardMapToSVG.getInstance().convertMapToSVG(svgGenerator, whiteBoardMap); // Finally, stream out SVG to the standard output using // UTF-8 encoding. boolean useCSS = true; // we want to use CSS style attributes // Writer out = new OutputStreamWriter(System.out, "UTF-8"); if (exportType.equals("svg")) { // OutputStream out = httpServletResponse.getOutputStream(); // httpServletResponse.setContentType("APPLICATION/OCTET-STREAM"); // httpServletResponse.setHeader("Content-Disposition","attachment; filename=\"" // + requestedFile + "\""); Writer out = httpServletResponse.getWriter(); svgGenerator.stream(out, useCSS); } else if (exportType.equals("png") || exportType.equals("jpg") || exportType.equals("gif") || exportType.equals("tif") || exportType.equals("pdf")) { String current_dir = getServletContext().getRealPath("/"); String working_dir = current_dir + OpenmeetingsVariables.UPLOAD_TEMP_DIR + File.separatorChar; String requestedFileSVG = fileName + "_" + CalendarPatterns.getTimeForStreamId(new Date()) + ".svg"; String resultFileName = fileName + "_" + CalendarPatterns.getTimeForStreamId(new Date()) + "." + exportType; log.debug("current_dir: " + current_dir); log.debug("working_dir: " + working_dir); log.debug("requestedFileSVG: " + requestedFileSVG); log.debug("resultFileName: " + resultFileName); File svgFile = new File(working_dir + requestedFileSVG); File resultFile = new File(working_dir + resultFileName); log.debug("svgFile: " + svgFile.getAbsolutePath()); log.debug("resultFile: " + resultFile.getAbsolutePath()); log.debug("svgFile P: " + svgFile.getPath()); log.debug("resultFile P: " + resultFile.getPath()); FileWriter out = new FileWriter(svgFile); svgGenerator.stream(out, useCSS); // Get file and handle download RandomAccessFile rf = new RandomAccessFile(resultFile.getAbsoluteFile(), "r"); httpServletResponse.reset(); httpServletResponse.resetBuffer(); OutputStream outStream = httpServletResponse.getOutputStream(); httpServletResponse.setContentType("APPLICATION/OCTET-STREAM"); httpServletResponse.setHeader("Content-Disposition", "attachment; filename=\"" + resultFileName + "\""); httpServletResponse.setHeader("Content-Length", "" + rf.length()); byte[] buffer = new byte[1024]; int readed = -1; while ((readed = rf.read(buffer, 0, buffer.length)) > -1) { outStream.write(buffer, 0, readed); } outStream.close(); rf.close(); out.flush(); out.close(); } } } catch (Exception er) { log.error("ERROR ", er); System.out.println("Error exporting: " + er); er.printStackTrace(); } }
From source file:app.utils.ACache.java
public byte[] getAsBinary(String key) { RandomAccessFile RAFile = null; boolean removeFile = false; try {/*from ww w . ja v a 2 s . co m*/ 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.example.psumaps.MapView.java
public static Bitmap convertToMutable(Bitmap imgIn) { try {/*from ww w . j a v a 2 s . c om*/ // this is the file going to use temporally to save the bytes. // This file will not be a image, it will store the raw image data. File file = new File(Environment.getExternalStorageDirectory() + File.separator + "temp.tmp"); // Open an RandomAccessFile // Make sure you have added uses-permission // android:name="android.permission.WRITE_EXTERNAL_STORAGE" // into AndroidManifest.xml file RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); // get the width and height of the source bitmap. int width = imgIn.getWidth(); int height = imgIn.getHeight(); Bitmap.Config type = imgIn.getConfig(); // Copy the byte to the file // Assume source bitmap loaded using options.inPreferredConfig = // Config.ARGB_8888; FileChannel channel = randomAccessFile.getChannel(); MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE, 0, imgIn.getRowBytes() * height); imgIn.copyPixelsToBuffer(map); // recycle the source bitmap, this will be no longer used. imgIn.recycle(); System.gc();// try to force the bytes from the imgIn to be released // Create a new bitmap to load the bitmap again. Probably the memory // will be available. imgIn = Bitmap.createBitmap(width, height, type); map.position(0); // load it back from temporary imgIn.copyPixelsFromBuffer(map); // close the temporary file and channel , then delete that also channel.close(); randomAccessFile.close(); // delete the temp file file.delete(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return imgIn; }
From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.fragments.EventGeneratorFragment.java
private float readCPUUsage() { try {/* w w w . ja v a 2 s .co m*/ RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r"); String load = reader.readLine(); String[] toks = load.split(" "); long idle1 = Long.parseLong(toks[5]); long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4]) + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]); try { Thread.sleep(360); } catch (Exception e) { } reader.seek(0); load = reader.readLine(); reader.close(); toks = load.split(" "); long idle2 = Long.parseLong(toks[5]); long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4]) + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]); return (float) (cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1)); } catch (IOException ex) { ex.printStackTrace(); } return 0; }
From source file:hornet.framework.clamav.service.ClamAVCheckService.java
/** * Rcupration du fichier stream.//from ww w .j av a2 s . c o m * * @param fileForTest * fichier de test * @param fileForTestSize * taille du fichier * @return MappedByteBuffer * @throws IOException * probleme de lecture */ protected MappedByteBuffer recupFichierStream(final File fileForTest, final long fileForTestSize) throws IOException { // Rcupration du fichier stream final RandomAccessFile raf = new RandomAccessFile(fileForTest, "r"); final FileChannel readChannel = raf.getChannel(); MappedByteBuffer bufFile = null; try { bufFile = readChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileForTestSize); } finally { if (readChannel != null) { try { readChannel.close(); } catch (final IOException e) { ClamAVCheckService.LOGGER.error("Erreur lors de la fermeture de la socket", e); } } if (raf != null) { try { raf.close(); } catch (final IOException e) { ClamAVCheckService.LOGGER.error("Erreur lors de la fermeture de la socket", e); } } } return bufFile; }
From source file:ome.services.blitz.impl.ExporterI.java
/** * Read size bytes, and transition to "waiting" If any exception is thrown, * the offset for the current file will not be updated. *//*w w w .j a v a 2s . c o m*/ private byte[] read(long pos, int size) throws ServerError { if (size > MAX_SIZE) { throw new ApiUsageException("Max read size is: " + MAX_SIZE); } byte[] buf = new byte[size]; RandomAccessFile ra = null; try { ra = new RandomAccessFile(file, "r"); long l = ra.length(); if (pos + size > l) { size = (int) (l - pos); } ra.seek(pos); int read = ra.read(buf); // Handle end of file if (read < 0) { buf = new byte[0]; } else if (read < size) { byte[] newBuf = new byte[read]; System.arraycopy(buf, 0, newBuf, 0, read); buf = newBuf; } } catch (IOException io) { throw new RuntimeException(io); } finally { if (ra != null) { try { ra.close(); } catch (IOException e) { log.warn("IOException on file close"); } } } return buf; }
From source file:com.example.android.vault.EncryptedDocument.java
/** * Decrypt and return parsed metadata section from this document. * * @throws DigestException if metadata fails MAC check, or if * {@link Document#COLUMN_DOCUMENT_ID} recorded in metadata is * unexpected./* w ww. jav a2 s. com*/ */ public JSONObject readMetadata() throws IOException, GeneralSecurityException { final RandomAccessFile f = new RandomAccessFile(mFile, "r"); try { assertMagic(f); // Only interested in metadata section final ByteArrayOutputStream metaOut = new ByteArrayOutputStream(); readSection(f, metaOut); final String rawMeta = metaOut.toString(StandardCharsets.UTF_8.name()); if (DEBUG_METADATA) { Log.d(TAG, "Found metadata for " + mDocId + ": " + rawMeta); } final JSONObject meta = new JSONObject(rawMeta); // Validate that metadata belongs to requested file if (meta.getLong(Document.COLUMN_DOCUMENT_ID) != mDocId) { throw new DigestException("Unexpected document ID"); } return meta; } catch (JSONException e) { throw new IOException(e); } finally { f.close(); } }
From source file:interfazGrafica.frmMoverRFC.java
public void mostrarPDF() { String curp = ""; curp = txtCapturaCurp.getText();/*from w ww. j ava 2s.co m*/ ArrayList<DocumentoRFC> Docs = new ArrayList<>(); DocumentoRFC sigExp; DocumentoRFC temporal; RFCescaneado tempo = new RFCescaneado(); //tempo.borrartemporal(); sigExp = expe.obtenerArchivosExp(); Nombre_Archivo = sigExp.getNombre(); nombreArchivo.setText(Nombre_Archivo); if (Nombre_Archivo != "") { doc = sigExp; System.out.println("Obtuvo el nombre del archivo."); System.out.println(doc.ruta + doc.nombre); String file = "C:\\escaneos\\Local\\Temporal\\" + doc.nombre; File arch = new File(file); System.out.println("Encontr el siguiente archivo:"); System.out.println(file); System.out.println(""); if (arch.exists()) { System.out.println("El archivo existe"); } try { System.out.println("Entr al try"); RandomAccessFile raf = new RandomAccessFile(file, "r"); System.out.println("Reconoc el archivo" + file); FileChannel channel = raf.getChannel(); System.out.println("Se abrio el canal"); ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); System.out.println("Channel map"); PDFFile pdffile = new PDFFile(buf); System.out.println("Creando un pdf file"); PDFPage page = pdffile.getPage(0); System.out.println("Obteniendo la pagina con " + 0); panelpdf2.showPage(page); System.out.println("mostrando el panel pdf2"); repaint(); System.gc(); buf.clear(); raf.close(); System.gc(); } catch (Exception ioe) { JOptionPane.showMessageDialog(null, "Error al abrir el archivo"); ioe.printStackTrace(); } } // tempo.borrartemporal(); }
From source file:com.owncloud.android.oc_framework.network.webdav.FileRequestEntity.java
@Override public void writeRequest(final OutputStream out) throws IOException { //byte[] tmp = new byte[4096]; ByteBuffer tmp = ByteBuffer.allocate(4096); int readResult = 0; // TODO(bprzybylski): each mem allocation can throw OutOfMemoryError we need to handle it // globally in some fashionable manner RandomAccessFile raf = new RandomAccessFile(mFile, "r"); FileChannel channel = raf.getChannel(); Iterator<OnDatatransferProgressListener> it = null; long transferred = 0; long size = mFile.length(); if (size == 0) size = -1;//from ww w . j a v a2 s. co m try { while ((readResult = channel.read(tmp)) >= 0) { out.write(tmp.array(), 0, readResult); tmp.clear(); transferred += readResult; synchronized (mDataTransferListeners) { it = mDataTransferListeners.iterator(); while (it.hasNext()) { it.next().onTransferProgress(readResult, transferred, size, mFile.getName()); } } } } catch (IOException io) { Log.e("FileRequestException", io.getMessage()); throw new RuntimeException( "Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really", io); } finally { channel.close(); raf.close(); } }