/** @tests java.nio.channels.FileLock#release() */ public void test_release() throws Exception { File file = File.createTempFile("test", "tmp"); file.deleteOnExit(); FileOutputStream fout = new FileOutputStream(file); FileChannel fileChannel = fout.getChannel(); FileLock fileLock = fileChannel.lock(); fileChannel.close(); try { fileLock.release(); fail("should throw ClosedChannelException"); } catch (ClosedChannelException e) { // expected } // release after release fout = new FileOutputStream(file); fileChannel = fout.getChannel(); fileLock = fileChannel.lock(); fileLock.release(); fileChannel.close(); try { fileLock.release(); fail("should throw ClosedChannelException"); } catch (ClosedChannelException e) { // expected } }
public static void main(String[] args) { try { BufferedImage img = ImageIO.read(new File(args[0])); BufferedImage intImg = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g2 = intImg.createGraphics(); g2.drawImage(img, null, null); Encoder enc = new Encoder(); // long startTime = System.nanoTime(); ByteBuffer frame = enc.encodeFrame(intImg, true); // long endTime = System.nanoTime(); // long time = (endTime - startTime) / 1000000; // System.out.print(String.format("Encode time %d ms\n", time)); FileOutputStream out = new FileOutputStream(args[1] + "Key.vp8"); out.getChannel().write(frame); out.close(); frame = enc.encodeFrame(intImg, false); out = new FileOutputStream(args[1] + "Inter.vp8"); out.getChannel().write(frame); out.close(); System.out.println("Success!"); } catch (IOException ex) { ex.printStackTrace(); throw new RuntimeException(ex); } }
// updateFiles - update linked files private void updateFiles() { // Update text files updateText(); // Write p1 file if (parent.iconCheckboxes[0].isSelected()) { try { int icon1new = parent.iconBoxes[0].getSelectedIndex(); if (icon1new != icon1curr) { String p1filename = iconList[icon1new].getIconFilename(); InputStream p1input = TSAEngine.class.getResourceAsStream( FOLDER_RESOURCES + getPrefixForMode() + p1filename + ICON_FILE_EXTENSION); FileOutputStream p1output = new FileOutputStream(p1Icon, false); p1output.getChannel().truncate(0); int in = p1input.read(); while (in != -1) { p1output.write(in); in = p1input.read(); } p1input.close(); p1output.close(); } } catch (IOException ioe) { System.err.println("Error writing to " + p1Icon.getName()); parent.iconCheckboxes[0].setSelected(false); } } // Write p2 file if (parent.iconCheckboxes[1].isSelected()) { try { int icon2new = parent.iconBoxes[1].getSelectedIndex(); if (icon2new != icon2curr) { String p2filename = iconList[icon2new].getIconFilename(); InputStream p2input = TSAEngine.class.getResourceAsStream( FOLDER_RESOURCES + getPrefixForMode() + p2filename + ICON_FILE_EXTENSION); FileOutputStream p2output = new FileOutputStream(p2Icon, false); p2output.getChannel().truncate(0); int in = p2input.read(); while (in != -1) { p2output.write(in); in = p2input.read(); } p2input.close(); p2output.close(); } } catch (IOException ioe) { System.err.println("Error writing to " + p2Icon.getName()); parent.iconCheckboxes[1].setSelected(false); } } }
@Override public boolean truncate(Path f, final long newLength) throws IOException { FileStatus status = getFileStatus(f); if (status == null) { throw new FileNotFoundException("File " + f + " not found"); } if (status.isDirectory()) { throw new IOException("Cannot truncate a directory (=" + f + ")"); } long oldLength = status.getLen(); if (newLength > oldLength) { throw new IllegalArgumentException( "Cannot truncate to a larger file size. Current size: " + oldLength + ", truncate size: " + newLength + "."); } try (FileOutputStream out = new FileOutputStream(pathToFile(f), true)) { try { out.getChannel().truncate(newLength); } catch (IOException e) { throw new FSError(e); } } return true; }
@Before public void setUp() throws Exception { // Download file for test URL website = new URL("http://archive.org/web/images/logo_wayback_210x77.png"); ReadableByteChannel resFile = Channels.newChannel(website.openStream()); // Create file File file = new File(pathTempFile); FileOutputStream fos = new FileOutputStream(pathTempFile); fos.getChannel().transferFrom(resFile, 0, Long.MAX_VALUE); // Save to MultipartFile FileInputStream input = new FileInputStream(file); multipartFile = new MockMultipartFile("file", file.getName(), "image/png", IOUtils.toByteArray(input)); fos.close(); input.close(); // Set paths attachmentService.setStoragePath(storagePath); attachmentService.setPathDefaultPreview(pathDefaultPreview); }
@Override public boolean renameTo(File dest) throws IOException { if (dest == null) { throw new NullPointerException("dest"); } if (byteBuf == null) { // empty file dest.createNewFile(); isRenamed = true; return true; } int length = byteBuf.readableBytes(); FileOutputStream outputStream = new FileOutputStream(dest); FileChannel fileChannel = outputStream.getChannel(); int written = 0; if (byteBuf.nioBufferCount() == 1) { ByteBuffer byteBuffer = byteBuf.nioBuffer(); while (written < length) { written += fileChannel.write(byteBuffer); } } else { ByteBuffer[] byteBuffers = byteBuf.nioBuffers(); while (written < length) { written += fileChannel.write(byteBuffers); } } fileChannel.force(false); fileChannel.close(); outputStream.close(); isRenamed = true; return written == length; }
public static void copyFile(@NotNull File from, @NotNull File to, boolean append) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { out = createOutputStream(to, append); in = new FileInputStream(from); FileChannel readChannel = in.getChannel(); FileChannel writeChannel = out.getChannel(); long size = readChannel.size(); for (long position = 0; position < size; ) { position += readChannel.transferTo(position, MB, writeChannel); } if (from.length() != to.length()) { throw new IOException("Failed to copy full contents from " + from + " to " + to); } } finally { close(in); close(out); } }
public static void copyFile(File srcFile, File destFile) throws Exception { int bufferSize = 2048; FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(destFile); FileChannel inChannel = in.getChannel(); FileChannel outChannel = out.getChannel(); ByteBuffer buffer = null; int length = -1; try { while (true) { if (inChannel.position() == inChannel.size()) { // finish copying break; } else if (inChannel.size() - inChannel.position() < length) { // copy last chunk of data length = (int) (inChannel.size() - inChannel.position()); } else { length = bufferSize; } buffer = ByteBuffer.allocateDirect(length); inChannel.read(buffer); buffer.flip(); outChannel.write(buffer); outChannel.force(false); } } finally { _close(inChannel); _close(in); _close(outChannel); _close(out); } }
/** * 使用FileChannel写文件 * * @throws IOException */ public static void writeByFileChannel() throws IOException { File file = new File("FileChannelWriterTest.txt"); if (file.exists()) { file.delete(); } FileOutputStream fos = new FileOutputStream(file); // 得到文件通道 FileChannel channel = fos.getChannel(); // 指定大小为1024的缓冲区 ByteBuffer buffer = ByteBuffer.allocate(1024); // 要写入文件的字符串 String greeting = "Hello Java NIO!"; // 把以上字符串逐字放入缓冲区 // for(int i = 0; i < greeting.length(); i++){ // buffer.putChar(greeting.charAt(i)); // } // 把以上字符一次性放入缓冲区 buffer.put(greeting.getBytes()); // 反转buffer buffer.flip(); // 缓冲区数据写入文件中 channel.write(buffer); // 关闭文件和通道流 channel.close(); fos.close(); System.out.println("Write file " + file.getName() + " Successfully!"); }
public static void saveFile(File file, String content, String charsetName) { // if (Utils.isEmpty(fileName) || Utils.isEmpty(content)) { // return; // } // logger.info("save file:" + fileName + " charset:" + charsetName); file.getParentFile().mkdirs(); Charset cs; if (null == charsetName || "".equals(charsetName)) { cs = Charset.defaultCharset(); } else { cs = Charset.forName(charsetName); } CharsetEncoder encoder = cs.newEncoder(); FileOutputStream os = null; FileChannel out = null; try { os = new FileOutputStream(file); out = os.getChannel(); out.write(encoder.encode(CharBuffer.wrap(content))); } catch (CharacterCodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { close(out); close(os); } }
@Override void executeExample() throws IOException { String audioEnglish = EXAMPLE_ROOT + "/count-video.mp4"; Movie countVideo = MovieCreator.build(audioEnglish); TextTrackImpl subTitleEng = new TextTrackImpl(); subTitleEng.getTrackMetaData().setLanguage("eng"); subTitleEng.getSubs().add(new TextTrackImpl.Line(5000, 6000, "Five")); subTitleEng.getSubs().add(new TextTrackImpl.Line(8000, 9000, "Four")); subTitleEng.getSubs().add(new TextTrackImpl.Line(12000, 13000, "Three")); subTitleEng.getSubs().add(new TextTrackImpl.Line(16000, 17000, "Two")); subTitleEng.getSubs().add(new TextTrackImpl.Line(20000, 21000, "one")); countVideo.addTrack(subTitleEng); TextTrackImpl subTitleDeu = SrtParser.parse(new FileInputStream(new File(EXAMPLE_ROOT + "/count-subs-deutsch.srt"))); subTitleDeu.getTrackMetaData().setLanguage("deu"); countVideo.addTrack(subTitleDeu); Container out = new DefaultMp4Builder().build(countVideo); FileOutputStream fos = new FileOutputStream(new File(EXAMPLE_ROOT + "/output.mp4")); FileChannel fc = fos.getChannel(); out.writeContainer(fc); fos.close(); }
private void copy(String here, String to) { // TODO Auto-generated method stub File s = new File(here); File t = new File(to); FileInputStream fi = null; FileOutputStream fo = null; FileChannel in = null; FileChannel out = null; try { fi = new FileInputStream(s); fo = new FileOutputStream(t); in = fi.getChannel(); // 得到对应的文件通道 out = fo.getChannel(); // 得到对应的文件通道 in.transferTo(0, in.size(), out); // 连接两个通道,并且从in通道读取,然后写入out通道 } catch (IOException e) { e.printStackTrace(); } finally { try { fi.close(); in.close(); fo.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
/** * Créer le fichier complet correspondant Copie et réassemble les données Supprime le fichier * temporaire et renvoi le nouveau fichier */ public synchronized FileShared tmpToComplete() { String name = this.getName(); name = name.substring(0, name.length() - ((String) App.config.get("tmpExtension")).length()); File complete = new File(App.config.get("downloadDir") + File.separator + name); if (complete.exists()) { throw new IllegalArgumentException(); } try { FileOutputStream writer_tmp = new FileOutputStream(complete, true); FileChannel writer = writer_tmp.getChannel(); int i; for (i = 0; i < this.nbPieces(); i++) { byte[] piece = this.readPieceTmpFile(i); Tools.write(writer, 0, piece); } writer.force(true); writer_tmp.close(); } catch (Exception e) { System.out.println("Unable to write complete file"); e.printStackTrace(); } this.delete(); return new FileShared(name); }
/** Initialise le header du fichier temporaire */ private void initHeaderTmpFile() { try { FileOutputStream writer_tmp = new FileOutputStream(this); FileChannel writer = writer_tmp.getChannel(); int offset = 0; // Taille de la clef Tools.write(writer, offset, _key.length()); offset += 4; // Clef Tools.write(writer, offset, _key); offset += _key.length(); // Size Tools.write(writer, offset, _size); offset += 4; // piecesize Tools.write(writer, offset, _piecesize); offset += 4; // Buffermap int i; for (i = 0; i < this.nbPieces(); i++) { Tools.write(writer, offset, -1); offset += 4; } writer.force(true); writer_tmp.close(); } catch (Exception e) { System.out.println("Unable to create a new tmp file"); e.printStackTrace(); } }
/** * 文件复制 * * @param s * @param t */ public static void fileCopy(File s, File t) { t.delete(); FileInputStream fi = null; FileOutputStream fo = null; FileChannel in = null; FileChannel out = null; try { fi = new FileInputStream(s); fo = new FileOutputStream(t); in = fi.getChannel(); // 得到对应的文件通道 out = fo.getChannel(); // 得到对应的文件通道 in.transferTo(0, in.size(), out); // 连接两个通道,并且从in通道读取,然后写入out通道 } catch (IOException e) { e.printStackTrace(); } finally { try { fi.close(); in.close(); fo.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
public void bt_resetAction(View v) { // Log.d( SystemInfo.TIG, TAG + "::bt_resetAction() - RESET DATABASE" ); // TODO implement option to dump db data on SD card try { // TODO this code is not enough tested - it shall rather show the idea!!! File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "//data//" + SystemInfo.TIG + ".db" + "//databases//" + SystemInfo.DB_NAME; String backupDBPath = SystemInfo.DB_NAME; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); if (currentDB.exists()) { fileInputStream = new FileInputStream(currentDB); FileChannel src = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(backupDB); FileChannel dst = fileOutputStream.getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); } } } catch (Exception e) { Log.w(SystemInfo.TIG, TAG + " saving database failed"); } // reset DB (dialog) AlertDialog.Builder yesnobox = new AlertDialog.Builder(this); yesnobox.setMessage("Really remove all data?"); yesnobox.setTitle("Confirm Database Reset"); yesnobox.setPositiveButton( "Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { for (int idx = 0; idx < DB_list.size(); ++idx) { DB_list.get(idx).data_reset(); } // TODO rm /* DB.data_reset(); DB.data_reset(); // XXX DB.data_reset(); DB.data_reset(); //*/ // refresh to battery view displayData(SystemInfo.PLOT_BATTERY_COMMENT, SystemInfo.DB_TABLENAME_BATTERY); } }); yesnobox.setNegativeButton( "No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // do nothing ; } }); yesnobox.show(); }
public static void downloadFile(String url, String outputName) throws IOException { URL website = new URL(url); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(outputName); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); }
private static void doCopyFile(File file, File file1, boolean flag) throws IOException { FileChannel filechannel; FileChannel filechannel1; FileChannel filechannel2; FileOutputStream fileoutputstream; FileChannel filechannel3; Object obj1; if (file1.exists() && file1.isDirectory()) { throw new IOException((new StringBuilder()).append("Destination '").append(file1).append("' exists but is a directory").toString()); } fileoutputstream = null; filechannel2 = null; obj1 = null; filechannel1 = null; filechannel3 = null; filechannel = null; Object obj = new FileInputStream(file); fileoutputstream = new FileOutputStream(file1); filechannel = filechannel3; filechannel1 = obj1; filechannel2 = ((FileInputStream) (obj)).getChannel(); filechannel = filechannel3; filechannel1 = filechannel2; filechannel3 = fileoutputstream.getChannel(); filechannel = filechannel3; filechannel1 = filechannel2; long l2 = filechannel2.size(); long l = 0L; goto _L1
public static void main(String[] args) throws IOException { Movie video = MovieCreator.build( Channels.newChannel( Mp4WithAudioDelayExample.class.getResourceAsStream("/count-video.mp4"))); Movie audio = MovieCreator.build( Channels.newChannel( Mp4WithAudioDelayExample.class.getResourceAsStream("/count-english-audio.mp4"))); List<Track> videoTracks = video.getTracks(); video.setTracks(new LinkedList<Track>()); List<Track> audioTracks = audio.getTracks(); for (Track videoTrack : videoTracks) { video.addTrack(new AppendTrack(videoTrack, videoTrack)); } for (Track audioTrack : audioTracks) { audioTrack.getTrackMetaData().setStartTime(10.0); video.addTrack(audioTrack); } IsoFile out = new DefaultMp4Builder().build(video); FileOutputStream fos = new FileOutputStream(new File(String.format("output.mp4"))); out.getBox(fos.getChannel()); fos.close(); }
public static DigestBlob resumeTransfer( BlobContainer blobContainer, String digest, UUID transferId, long currentPos) { DigestBlob digestBlob = new DigestBlob(blobContainer, digest, transferId); digestBlob.file = getTmpFilePath(blobContainer, digest, transferId); try { logger.trace("Resuming DigestBlob {}. CurrentPos {}", digest, currentPos); digestBlob.headFileChannel = new FileOutputStream(digestBlob.file, false).getChannel(); digestBlob.headLength = currentPos; digestBlob.headSize = new AtomicLong(); digestBlob.headCatchedUpLatch = new CountDownLatch(1); RandomAccessFile raf = new RandomAccessFile(digestBlob.file, "rw"); raf.setLength(currentPos); raf.close(); FileOutputStream outputStream = new FileOutputStream(digestBlob.file, true); digestBlob.fileChannel = outputStream.getChannel(); } catch (IOException ex) { logger.error("error resuming transfer of {}, id: {}", ex, digest, transferId); return null; } return digestBlob; }
/** * Based on <a href="http://www.screaming-penguin.com/node/7749">Backing up your Android SQLite * database to the SD card</a> * * @param src * @param dst * @return true if success * @throws IOException */ boolean copyFile(File src, File dst) throws IOException { long sizeIn = -1; long sizeCopied = 0; boolean ok = false; if (src != null && src.exists()) { sizeIn = src.length(); if (!dst.createNewFile()) { MyLog.e(this, "New file was not created: '" + dst.getCanonicalPath() + "'"); } else if (src.getCanonicalPath().compareTo(dst.getCanonicalPath()) == 0) { MyLog.d(this, "Cannot copy to itself: '" + src.getCanonicalPath() + "'"); } else { FileInputStream fileInputStream = null; java.nio.channels.FileChannel inChannel = null; FileOutputStream fileOutputStream = null; java.nio.channels.FileChannel outChannel = null; try { fileInputStream = new FileInputStream(src); inChannel = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(dst); outChannel = fileOutputStream.getChannel(); sizeCopied = inChannel.transferTo(0, inChannel.size(), outChannel); ok = (sizeIn == sizeCopied); } finally { DbUtils.closeSilently(outChannel); DbUtils.closeSilently(fileOutputStream); DbUtils.closeSilently(inChannel); DbUtils.closeSilently(fileInputStream); } } } MyLog.d(this, "Copied " + sizeCopied + " bytes of " + sizeIn); return ok; }
/** * 监测复制进度(留意buffer的大小,对速度有很大影响) * * @param source * @param target */ public static void nioBufferCopy(File source, File target) { FileChannel in = null; FileChannel out = null; FileInputStream inStream = null; FileOutputStream outStream = null; try { inStream = new FileInputStream(source); outStream = new FileOutputStream(target); in = inStream.getChannel(); out = outStream.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(4096); while (in.read(buffer) != -1) { buffer.flip(); out.write(buffer); buffer.clear(); } } catch (IOException e) { e.printStackTrace(); } finally { close(inStream); close(in); close(outStream); close(out); } }
public static boolean downloadOCSSWInstaller() { if (isOcsswInstalScriptDownloadSuccessful()) { return ocsswInstalScriptDownloadSuccessful; } try { URL website = new URL(OCSSW_INSTALLER_URL); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(TMP_OCSSW_INSTALLER); fos.getChannel().transferFrom(rbc, 0, 1 << 24); fos.close(); (new File(TMP_OCSSW_INSTALLER)).setExecutable(true); ocsswInstalScriptDownloadSuccessful = true; } catch (MalformedURLException malformedURLException) { handleException("URL for downloading install_ocssw.py is not correct!"); } catch (FileNotFoundException fileNotFoundException) { handleException( "ocssw installation script failed to download. \n" + "Please check network connection or 'seadas.ocssw.root' variable in the 'seadas.config' file. \n" + "possible cause of error: " + fileNotFoundException.getMessage()); } catch (IOException ioe) { handleException( "ocssw installation script failed to download. \n" + "Please check network connection or 'seadas.ocssw.root' variable in the \"seadas.config\" file. \n" + "possible cause of error: " + ioe.getLocalizedMessage()); } finally { return ocsswInstalScriptDownloadSuccessful; } }
/** * Esse metodo serve para copiar um ou mais arquivos para outro diretorio. Exemplo: copy(new * String[]{"/home/andre/teste.txt","/home/andre/teste2.txt" },"/home/ariella/"); * * @param filenames * @param dest * @throws TSApplicationException */ public void copy(String[] filenames, String dest) throws TSApplicationException { String[] fileNamesNovo = new String[filenames.length]; FileOutputStream fout = null; FileInputStream fin = null; // Compress the files try { for (int i = 0; i < filenames.length; i++) { String novoArquivo = filenames[i].substring(filenames[i].lastIndexOf("/") + 1); fileNamesNovo[i] = dest + novoArquivo; // Cria a stream para ler o arquivo original fin = new FileInputStream(filenames[i]); fout = new FileOutputStream(fileNamesNovo[i]); // Cria a stream para gravar o arquivo de c�pia // Usa as streams para criar os canais correspondentes FileChannel in = fin.getChannel(); FileChannel outChannel = fout.getChannel(); // N�mero de bytes do arquivo original long numbytes = in.size(); // Transfere todo o volume para o arquivo de c�pia. in.transferTo(0, numbytes, outChannel); } } catch (FileNotFoundException e) { throw new TSApplicationException(TSConstant.MENSAGEM_FILE_NOT_FOUND); } catch (IOException e) { throw new TSApplicationException(TSConstant.MENSAGEM_ERRO_ENTRADA_SAIDA); } }
private static boolean unsafeDownloadToFile(String url, File output) throws IOException { output.createNewFile(); FileOutputStream fos = new FileOutputStream(output); fos.getChannel().transferFrom(Channels.newChannel(requestStreamHttp(url)), 0, Long.MAX_VALUE); fos.close(); return true; }
public static ChannelByteIO stdIO() { FileInputStream input = new FileInputStream(FileDescriptor.in); FileOutputStream output = new FileOutputStream(FileDescriptor.out); FileChannel in = input.getChannel(); FileChannel out = output.getChannel(); return new ChannelByteIO(in, out); }
public static void reconstructTurtle(File partFolder, File reconstructed) throws IOException { Path tmpOut = Files.createTempFile(partFolder.toPath(), "reconstr", ".tmp"); FileOutputStream dstOut = new FileOutputStream(tmpOut.toFile()); FileChannel dstOutChannel = dstOut.getChannel(); try { if (!Files.isDirectory(partFolder.toPath())) throw new IOException("Not a directory: " + partFolder); File[] fileList = FileUtils.listFiles(partFolder, new PrefixFileFilter("part"), TrueFileFilter.TRUE) .toArray(new File[0]); Arrays.sort(fileList); RandomAccessFile inputFile; inputFile = new RandomAccessFile(fileList[0], "r"); inputFile.getChannel().transferTo(0, inputFile.length(), dstOutChannel); inputFile.close(); for (int i = 1; i < fileList.length; i++) { inputFile = new RandomAccessFile(fileList[i], "r"); long lastPrefix = findTurtlePrefixEnd(inputFile); inputFile .getChannel() .transferTo(lastPrefix, inputFile.length() - lastPrefix, dstOutChannel); inputFile.close(); } } finally { dstOut.close(); } Files.move( tmpOut, reconstructed.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); FileUtils.deleteQuietly(tmpOut.toFile()); FileUtils.deleteQuietly(partFolder); }
public static DataFileAccessorImpl create( final File file, final Date startDate, final Date endDate) throws Exception { logger.debug("Creating new file: {}", file); if (!file.createNewFile()) { throw new IllegalStateException( String.format("Unable to create file %s, already exists", file)); } final FileOutputStream out = new FileOutputStream(file); try { final FileChannel channel = out.getChannel(); final ByteBuffer buffer = ByteBuffer.allocate(100); buffer.putInt(0x1202); // magic marker buffer.putInt(0x0101); // version buffer.putLong(startDate.getTime()); // start timestamp buffer.putLong(endDate.getTime()); // end timestamp buffer.flip(); while (buffer.hasRemaining()) { final int rc = channel.write(buffer); logger.debug("Header written - {} bytes", rc); } return new DataFileAccessorImpl(file); } finally { out.close(); } }
/** * Internal copy file method. * * @param srcFile the validated source file, must not be <code>null</code> * @param destFile the validated destination file, must not be <code>null</code> * @throws IOException if an error occurs */ private static void doCopyFile(File srcFile, File destFile) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size) { count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos); pos += output.transferFrom(input, pos, count); } } finally { Streams.closeQuietly(output); Streams.closeQuietly(fos); Streams.closeQuietly(input); Streams.closeQuietly(fis); } if (srcFile.length() != destFile.length()) { throw new IOException( "Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } }
// from https://gist.github.com/889747 // TODO use Jakarta Commons IO..! This implementation needs to be improved. private static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileInputStream fIn = null; FileOutputStream fOut = null; FileChannel source = null; FileChannel destination = null; try { fIn = new FileInputStream(sourceFile); source = fIn.getChannel(); fOut = new FileOutputStream(destFile); destination = fOut.getChannel(); long transfered = 0; long bytes = source.size(); while (transfered < bytes) { transfered += destination.transferFrom(source, 0, source.size()); destination.position(transfered); } } finally { if (source != null) { source.close(); } else if (fIn != null) { fIn.close(); } if (destination != null) { destination.close(); } else if (fOut != null) { fOut.close(); } } }