List of usage examples for java.nio.channels FileChannel close
public final void close() throws IOException
From source file:Util.java
public void write(File dest, InputStream in) { FileChannel channel = null; try {/*from w w w . j a v a2 s . c o m*/ channel = new FileOutputStream(dest).getChannel(); } catch (FileNotFoundException e) { System.out.println(e); } try { int byteCount = 0; byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = in.read(buffer)) != -1) { ByteBuffer byteBuffer = ByteBuffer.wrap(buffer, 0, bytesRead); channel.write(byteBuffer); byteCount += bytesRead; } } catch (IOException e) { System.out.println(e); } finally { try { if (channel != null) { channel.close(); } if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } }
From source file:org.wso2.msf4j.internal.entitywriter.FileEntityWriter.java
/** * Write the entity to the carbon message. *//*from w w w . ja v a 2s. c o m*/ @Override public void writeData(CarbonMessage carbonMessage, File file, String mediaType, int chunkSize, CarbonCallback cb) { if (mediaType == null || mediaType.equals(MediaType.WILDCARD)) { try { mediaType = MimeMapper.getMimeType(FilenameUtils.getExtension(file.getName())); } catch (MimeMappingException e) { mediaType = MediaType.WILDCARD; } } try { FileChannel fileChannel = new FileInputStream(file).getChannel(); if (chunkSize == Response.NO_CHUNK || chunkSize == Response.DEFAULT_CHUNK_SIZE) { chunkSize = DEFAULT_CHUNK_SIZE; } carbonMessage.setHeader(Constants.HTTP_TRANSFER_ENCODING, CHUNKED); carbonMessage.setHeader(Constants.HTTP_CONTENT_TYPE, mediaType); carbonMessage.setBufferContent(false); cb.done(carbonMessage); ByteBuffer buffer = ByteBuffer.allocate(chunkSize); while (fileChannel.read(buffer) != -1) { buffer.flip(); carbonMessage.addMessageBody(buffer); } fileChannel.close(); carbonMessage.setEndOfMsgAdded(true); } catch (IOException e) { throw new RuntimeException("Error occurred while reading from file", e); } }
From source file:org.linagora.linshare.webservice.userv2.impl.FlowDocumentUploaderRestServiceImpl.java
@Path("/") @POST//w w w. ja v a 2 s .co m @Consumes("multipart/form-data") @Override public FlowDto uploadChunk(@Multipart(CHUNK_NUMBER) long chunkNumber, @Multipart(TOTAL_CHUNKS) long totalChunks, @Multipart(CHUNK_SIZE) long chunkSize, @Multipart(CURRENT_CHUNK_SIZE) long currentChunkSize, @Multipart(TOTAL_SIZE) long totalSize, @Multipart(IDENTIFIER) String identifier, @Multipart(FILENAME) String filename, @Multipart(RELATIVE_PATH) String relativePath, @Multipart(FILE) InputStream file, MultipartBody body, @Multipart(value = WORK_GROUP_UUID, required = false) String workGroupUuid, @Multipart(value = WORK_GROUP_FOLDER_UUID, required = false) String workGroupFolderUuid, @Multipart(value = ASYNC_TASK, required = false) boolean async) throws BusinessException { logger.debug("upload chunk number : " + chunkNumber); identifier = cleanIdentifier(identifier); boolean isValid = FlowUploaderUtils.isValid(chunkNumber, chunkSize, totalSize, identifier, filename); Validate.isTrue(isValid); checkIfMaintenanceIsEnabled(); FlowDto flow = new FlowDto(chunkNumber); try { logger.debug("writing chunk number : " + chunkNumber); java.nio.file.Path tempFile = FlowUploaderUtils.getTempFile(identifier, chunkedFiles); ChunkedFile currentChunkedFile = chunkedFiles.get(identifier); if (!currentChunkedFile.hasChunk(chunkNumber)) { FileChannel fc = FileChannel.open(tempFile, StandardOpenOption.CREATE, StandardOpenOption.APPEND); ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(file, output); fc.write(ByteBuffer.wrap(output.toByteArray()), (chunkNumber - 1) * chunkSize); fc.close(); if (sizeValidation) { if (output.size() != currentChunkSize) { String msg = String.format("File size does not match, found : %1$d, announced : %2$d", output.size(), currentChunkSize); logger.error(msg); flow.setChunkUploadSuccess(false); flow.setErrorMessage(msg); return flow; } } currentChunkedFile.addChunk(chunkNumber); } else { logger.error("currentChunkedFile.hasChunk(chunkNumber) !!! " + currentChunkedFile); logger.error("chunkedNumber skipped : " + chunkNumber); } logger.debug("nb uploading files : " + chunkedFiles.size()); logger.debug("current chuckedfile uuid : " + identifier); logger.debug("current chuckedfiles" + chunkedFiles.toString()); if (FlowUploaderUtils.isUploadFinished(identifier, chunkSize, totalSize, chunkedFiles)) { flow.setLastChunk(true); logger.debug("upload finished : " + chunkNumber + " : " + identifier); InputStream inputStream = Files.newInputStream(tempFile, StandardOpenOption.READ); File tempFile2 = getTempFile(inputStream, "rest-flowuploader", filename); if (sizeValidation) { long currSize = tempFile2.length(); if (currSize != totalSize) { String msg = String.format("File size does not match, found : %1$d, announced : %2$d", currSize, totalSize); logger.error(msg); flow.setChunkUploadSuccess(false); flow.setErrorMessage(msg); return flow; } } EntryDto uploadedDocument = new EntryDto(); flow.setIsAsync(async); boolean isWorkGroup = !Strings.isNullOrEmpty(workGroupUuid); if (async) { logger.debug("Async mode is used"); // Asynchronous mode AccountDto actorDto = documentFacade.getAuthenticatedAccountDto(); AsyncTaskDto asyncTask = null; try { if (isWorkGroup) { ThreadEntryTaskContext threadEntryTaskContext = new ThreadEntryTaskContext(actorDto, actorDto.getUuid(), workGroupUuid, tempFile2, filename, workGroupFolderUuid); asyncTask = asyncTaskFacade.create(totalSize, getTransfertDuration(identifier), filename, null, AsyncTaskType.THREAD_ENTRY_UPLOAD); ThreadEntryUploadAsyncTask task = new ThreadEntryUploadAsyncTask(threadEntryAsyncFacade, threadEntryTaskContext, asyncTask); taskExecutor.execute(task); flow.completeAsyncTransfert(asyncTask); } else { DocumentTaskContext documentTaskContext = new DocumentTaskContext(actorDto, actorDto.getUuid(), tempFile2, filename, null, null); asyncTask = asyncTaskFacade.create(totalSize, getTransfertDuration(identifier), filename, null, AsyncTaskType.DOCUMENT_UPLOAD); DocumentUploadAsyncTask task = new DocumentUploadAsyncTask(documentAsyncFacade, documentTaskContext, asyncTask); taskExecutor.execute(task); flow.completeAsyncTransfert(asyncTask); } } catch (Exception e) { logAsyncFailure(asyncTask, e); deleteTempFile(tempFile2); ChunkedFile remove = chunkedFiles.remove(identifier); Files.deleteIfExists(remove.getPath()); throw e; } } else { try { if (isWorkGroup) { uploadedDocument = threadEntryFacade.create(null, workGroupUuid, workGroupFolderUuid, tempFile2, filename); } else { uploadedDocument = documentFacade.create(tempFile2, filename, "", null); } flow.completeTransfert(uploadedDocument); } finally { deleteTempFile(tempFile2); ChunkedFile remove = chunkedFiles.remove(identifier); if (remove != null) { Files.deleteIfExists(remove.getPath()); } else { logger.error("Should not happen !!!"); logger.error("chunk number: " + chunkNumber); logger.error("chunk identifier: " + identifier); logger.error("chunk filename: " + filename); logger.error("chunks : " + chunkedFiles.toString()); } } } return flow; } else { logger.debug("upload pending "); flow.setChunkUploadSuccess(true); } } catch (BusinessException e) { logger.error(e.getMessage()); logger.debug("Exception : ", e); flow.setChunkUploadSuccess(false); flow.setErrorMessage(e.getMessage()); flow.setErrCode(e.getErrorCode().getCode()); } catch (Exception e) { logger.error(e.getMessage()); logger.debug("Exception : ", e); flow.setChunkUploadSuccess(false); flow.setErrorMessage(e.getMessage()); } return flow; }
From source file:cn.wanghaomiao.seimi.struct.Response.java
public void saveTo(File targetFile) { FileChannel fo = null; try {/*w ww . j ava 2s.com*/ File pf = targetFile.getParentFile(); if (!pf.exists()) { pf.mkdirs(); } fo = new FileOutputStream(targetFile).getChannel(); if (BodyType.TEXT.equals(bodyType)) { fo.write(ByteBuffer.wrap(getContent().getBytes())); } else { fo.write(ByteBuffer.wrap(getData())); } } catch (Exception e) { throw new RuntimeException(e); } finally { if (fo != null) { try { fo.close(); } catch (IOException ignore) { logger.error(ignore.getMessage(), ignore); } } } }
From source file:org.granite.grails.web.GrailsWebSWFServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID, grailsAttributes); // Get the name of the Groovy script (intern the name so that we can lock on it) String pageName = "/swf" + request.getServletPath(); Resource requestedFile = getResourceForUri(pageName); File swfFile = requestedFile.getFile(); if (swfFile == null || !swfFile.exists()) { response.sendError(404, "\"" + pageName + "\" not found."); return;// ww w .j a v a2 s . c o m } response.setContentType("application/x-shockwave-flash"); response.setContentLength((int) swfFile.length()); response.setBufferSize((int) swfFile.length()); response.setDateHeader("Expires", 0); FileInputStream is = null; FileChannel inChan = null; try { is = new FileInputStream(swfFile); OutputStream os = response.getOutputStream(); inChan = is.getChannel(); long fSize = inChan.size(); MappedByteBuffer mBuf = inChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize); byte[] buf = new byte[(int) fSize]; mBuf.get(buf); os.write(buf); } finally { if (is != null) { IOUtils.closeQuietly(is); } if (inChan != null) { try { inChan.close(); } catch (IOException ignored) { } } } }
From source file:org.etudes.jforum.view.install.InstallAction.java
private void copyFile(String from, String to) throws Exception { FileChannel source = new FileInputStream(new File(from)).getChannel(); FileChannel dest = new FileOutputStream(new File(to)).getChannel(); source.transferTo(0, source.size(), dest); source.close(); dest.close();//from w w w . j a v a 2 s .c o m }
From source file:org.apache.bookkeeper.bookie.BookieJournalTest.java
private void writePartialIndexFileForLedger(File indexDir, long ledgerId, byte[] masterKey, boolean truncateToMasterKey) throws Exception { File fn = new File(indexDir, IndexPersistenceMgr.getLedgerName(ledgerId)); fn.getParentFile().mkdirs();//from w w w. j av a 2s . c om FileInfo fi = new FileInfo(fn, masterKey); // force creation of index file fi.write(new ByteBuffer[] { ByteBuffer.allocate(0) }, 0); fi.close(true); // file info header int headerLen = 8 + 4 + masterKey.length; // truncate the index file int leftSize; if (truncateToMasterKey) { leftSize = r.nextInt(headerLen); } else { leftSize = headerLen + r.nextInt(1024 - headerLen); } FileChannel fc = new RandomAccessFile(fn, "rw").getChannel(); fc.truncate(leftSize); fc.close(); }
From source file:com.thoughtworks.go.config.GoConfigFileWriter.java
public synchronized void writeToConfigXmlFile(String content) { FileChannel channel = null; FileOutputStream outputStream = null; FileLock lock = null;//from w w w .j a v a2 s .c o m try { RandomAccessFile randomAccessFile = new RandomAccessFile(fileLocation(), "rw"); channel = randomAccessFile.getChannel(); lock = channel.lock(); randomAccessFile.seek(0); randomAccessFile.setLength(0); outputStream = new FileOutputStream(randomAccessFile.getFD()); IOUtils.write(content, outputStream, UTF_8); } catch (Exception e) { throw new RuntimeException(e); } finally { if (channel != null && lock != null) { try { lock.release(); channel.close(); IOUtils.closeQuietly(outputStream); } catch (IOException e) { LOGGER.error("Error occured when releasing file lock and closing file.", e); } } } }
From source file:test.other.T_DaoTest.java
public void test2() throws SQLException, IOException { System.out.println(System.nanoTime() / 1000000); ResultSet rs = conn.createStatement().executeQuery("select content from fc_Post where id = 15"); rs.next();/* ww w . jav a2s .co m*/ String text = rs.getString(1); System.out.println(text.length()); System.out.println(System.nanoTime() / 1000000); @SuppressWarnings("resource") FileChannel rwChannel = new RandomAccessFile("textfile.txt", "rw").getChannel(); ByteBuffer wrBuf = rwChannel.map(FileChannel.MapMode.READ_WRITE, 0, text.length() + 10); int lg = text.length() / 1000000; int pos = 0; byte[] buf = new byte[text.length() / 1000000]; System.out.println(System.nanoTime() / 1000000); for (int i = 0; i < 1000000; i++) { System.arraycopy(text.getBytes(), pos, buf, 0, lg); wrBuf.put(buf); pos += lg; } System.out.println(System.nanoTime() / 1000000); rwChannel.close(); }
From source file:com.example.psumaps.MapView.java
public static Bitmap convertToMutable(Bitmap imgIn) { try {/* w w w. ja va2 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; }