List of usage examples for java.nio.channels FileChannel write
public final long write(ByteBuffer[] srcs) throws IOException
From source file:org.commoncrawl.util.S3Downloader.java
public static void main(String[] args) { boolean isRequesterPays = args[3].equals("1"); S3Downloader downloader = new S3Downloader(args[0], args[1], args[2], isRequesterPays); String itemToFetch = args[4]; try {//from w w w . j ava 2s . co m downloader.initialize(new Callback() { Map<String, FileChannel> channelMap = new HashMap<String, FileChannel>(); public boolean contentAvailable(int itemId, String itemKey, NIOBufferList contentBuffer) { LOG.info("Key:" + itemKey + " GOT:" + contentBuffer.available() + " Bytes"); FileChannel channel = channelMap.get(itemKey); if (channel != null) { try { while (contentBuffer.available() != 0) { ByteBuffer buffer = contentBuffer.read(); channel.write(buffer); } return true; } catch (IOException e) { LOG.error(StringUtils.stringifyException(e)); return false; } } return false; } public void downloadComplete(int itemId, String itemKey) { LOG.info("Key:" + itemKey + " DownloadComplete"); FileChannel channel = channelMap.get(itemKey); if (channel != null) { try { channel.close(); } catch (IOException e) { LOG.error(StringUtils.stringifyException(e)); } } channelMap.remove(itemKey); } public void downloadFailed(int itemId, String itemKey, String errorCode) { LOG.info("Key:" + itemKey + " DownloadFailed. ErrorCode:" + errorCode); FileChannel channel = channelMap.get(itemKey); if (channel != null) { try { channel.close(); } catch (IOException e) { LOG.error(StringUtils.stringifyException(e)); } } channelMap.remove(itemKey); } public boolean downloadStarting(int itemId, String itemKey, int contentLength) { LOG.info("Key:" + itemKey + " DownloadStarting - ContentLength:" + contentLength); File file = new File("/tmp/" + itemKey); if (file.exists()) file.delete(); file.getParentFile().mkdirs(); FileOutputStream fileHandle = null; try { fileHandle = new FileOutputStream(file); //LOG.info("Key:" + itemKey + " Created File:" + file.getAbsolutePath()); channelMap.put(itemKey, fileHandle.getChannel()); } catch (IOException e) { LOG.error(StringUtils.stringifyException(e)); if (fileHandle != null) try { fileHandle.close(); } catch (IOException e1) { } return false; } return true; } }); downloader.fetchItem(itemToFetch); downloader.waitForCompletion(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:MainClass.java
public static void main(String[] args) { String[] phrases = { "A", "B 1", "C 1.3" }; String dirname = "C:/test"; String filename = "Phrases.txt"; File dir = new File(dirname); File aFile = new File(dir, filename); FileOutputStream outputFile = null; try {/* w ww . ja va 2 s . c o m*/ outputFile = new FileOutputStream(aFile, true); } catch (FileNotFoundException e) { e.printStackTrace(System.err); } FileChannel outChannel = outputFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate(1024); System.out.println(buf.position()); System.out.println(buf.limit()); System.out.println(buf.capacity()); CharBuffer charBuf = buf.asCharBuffer(); System.out.println(charBuf.position()); System.out.println(charBuf.limit()); System.out.println(charBuf.capacity()); Formatter formatter = new Formatter(charBuf); int number = 0; for (String phrase : phrases) { formatter.format("%n %s", ++number, phrase); System.out.println(charBuf.position()); System.out.println(charBuf.limit()); System.out.println(charBuf.capacity()); charBuf.flip(); System.out.println(charBuf.position()); System.out.println(charBuf.limit()); System.out.println(charBuf.length()); buf.limit(2 * charBuf.length()); // Set byte buffer limit System.out.println(buf.position()); System.out.println(buf.limit()); System.out.println(buf.remaining()); try { outChannel.write(buf); buf.clear(); charBuf.clear(); } catch (IOException e) { e.printStackTrace(System.err); } } try { outputFile.close(); } catch (IOException e) { e.printStackTrace(System.err); } }
From source file:Lock.java
public static void main(String args[]) throws IOException, InterruptedException { RandomAccessFile file = null; // The file we'll lock FileChannel f = null; // The channel to the file FileLock lock = null; // The lock object we hold try { // The finally clause closes the channel and releases the lock // We use a temporary file as the lock file. String tmpdir = System.getProperty("java.io.tmpdir"); String filename = Lock.class.getName() + ".lock"; File lockfile = new File(tmpdir, filename); // Create a FileChannel that can read and write that file. // Note that we rely on the java.io package to open the file, // in read/write mode, and then just get a channel from it. // This will create the file if it doesn't exit. We'll arrange // for it to be deleted below, if we succeed in locking it. file = new RandomAccessFile(lockfile, "rw"); f = file.getChannel();/*from ww w.j a va 2 s . c om*/ // Try to get an exclusive lock on the file. // This method will return a lock or null, but will not block. // See also FileChannel.lock() for a blocking variant. lock = f.tryLock(); if (lock != null) { // We obtained the lock, so arrange to delete the file when // we're done, and then write the approximate time at which // we'll relinquish the lock into the file. lockfile.deleteOnExit(); // Just a temporary file // First, we need a buffer to hold the timestamp ByteBuffer bytes = ByteBuffer.allocate(8); // a long is 8 bytes // Put the time in the buffer and flip to prepare for writing // Note that many Buffer methods can be "chained" like this. bytes.putLong(System.currentTimeMillis() + 10000).flip(); f.write(bytes); // Write the buffer contents to the channel f.force(false); // Force them out to the disk } else { // We didn't get the lock, which means another instance is // running. First, let the user know this. System.out.println("Another instance is already running"); // Next, we attempt to read the file to figure out how much // longer the other instance will be running. Since we don't // have a lock, the read may fail or return inconsistent data. try { ByteBuffer bytes = ByteBuffer.allocate(8); f.read(bytes); // Read 8 bytes from the file bytes.flip(); // Flip buffer before extracting bytes long exittime = bytes.getLong(); // Read bytes as a long // Figure out how long that time is from now and round // it to the nearest second. long secs = (exittime - System.currentTimeMillis() + 500) / 1000; // And tell the user about it. System.out.println("Try again in about " + secs + " seconds"); } catch (IOException e) { // This probably means that locking is enforced by the OS // and we were prevented from reading the file. } // This is an abnormal exit, so set an exit code. System.exit(1); } // Simulate a real application by sleeping for 10 seconds. System.out.println("Starting..."); Thread.sleep(10000); System.out.println("Exiting."); } finally { // Always release the lock and close the file // Closing the RandomAccessFile also closes its FileChannel. if (lock != null && lock.isValid()) lock.release(); if (file != null) file.close(); } }
From source file:Main.java
private static void writeFileFromBytes(final File file, final byte[] bytes) { FileChannel fc = null; try {/*from w w w . ja v a 2 s.c o m*/ fc = new FileOutputStream(file, false).getChannel(); fc.write(ByteBuffer.wrap(bytes)); fc.force(true); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fc != null) { fc.close(); } } catch (IOException e) { e.printStackTrace(); } } }
From source file:Main.java
public static void toFile(ByteBuffer buffer, File file) throws IOException { RandomAccessFile raf = null;/*from w w w.j a v a 2 s . c om*/ FileChannel channel = null; try { raf = new RandomAccessFile(file, "rw"); channel = raf.getChannel(); channel.write(buffer); channel.force(false /*metadata*/); channel.close(); raf.close(); } finally { if (channel != null) { try { channel.close(); } catch (IOException e) { // Ignored. } } if (raf != null) { try { raf.close(); } catch (IOException e) { // Ignored. } } } }
From source file:Main.java
/** Copia un fichero. * @param source Fichero origen con el contenido que queremos copiar. * @param dest Fichero destino de los datos. * @throws IOException SI ocurre algun problema durante la copia */ public static void copyFile(final File source, final File dest) throws IOException { if (source == null || dest == null) { throw new IllegalArgumentException("Ni origen ni destino de la copia pueden ser nulos"); //$NON-NLS-1$ }/* ww w.ja v a 2 s. com*/ final FileInputStream is = new FileInputStream(source); final FileOutputStream os = new FileOutputStream(dest); final FileChannel in = is.getChannel(); final FileChannel out = os.getChannel(); final MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, in.size()); out.write(buf); in.close(); out.close(); is.close(); os.close(); }
From source file:yui.classes.utils.IOUtils.java
public static void fastCopy(File source, File dest) throws IOException { FileInputStream fi = new FileInputStream(source); FileChannel fic = fi.getChannel(); MappedByteBuffer mbuf = fic.map(FileChannel.MapMode.READ_ONLY, 0, source.length()); fic.close();/*from ww w . java 2 s .co m*/ fi.close(); FileOutputStream fo = new FileOutputStream(dest); FileChannel foc = fo.getChannel(); foc.write(mbuf); foc.close(); fo.close(); }
From source file:com.alibaba.otter.shared.common.utils.NioUtilsPerformance.java
public static void channelTest(File source, File target) throws Exception { FileInputStream fis = null;/*from w w w . j ava2 s .com*/ FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(target); FileChannel sChannel = fis.getChannel(); FileChannel tChannel = fos.getChannel(); target.createNewFile(); ByteBuffer buffer = ByteBuffer.allocate(16 * 1024); while (sChannel.read(buffer) > 0) { buffer.flip(); tChannel.write(buffer); buffer.clear(); } tChannel.close(); sChannel.close(); } finally { IOUtils.closeQuietly(fis); IOUtils.closeQuietly(fos); } }
From source file:MainClass.java
private static void createFile() throws Exception { long[] primes = new long[] { 1, 2, 3, 5, 7 }; File aFile = new File("C:/primes.bin"); FileOutputStream outputFile = new FileOutputStream(aFile); FileChannel file = outputFile.getChannel(); final int BUFFERSIZE = 100; ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE); LongBuffer longBuf = buf.asLongBuffer(); int primesWritten = 0; while (primesWritten < primes.length) { longBuf.put(primes, primesWritten, min(longBuf.capacity(), primes.length - primesWritten)); buf.limit(8 * longBuf.position()); file.write(buf); primesWritten += longBuf.position(); longBuf.clear();//from w w w . ja v a2s . co m buf.clear(); } System.out.println("File written is " + file.size() + "bytes."); outputFile.close(); }
From source file:ja.lingo.engine.util.EngineFiles.java
private static void appendFile(String fileName, FileOutputStream fos, boolean prependWithLength) throws IOException { FileInputStream fis = new FileInputStream(fileName); FileChannel fic = fis.getChannel(); FileChannel foc = fos.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(COPY_BUFFER_SIZE); // put header: length (1 int = 4 bytes) if (prependWithLength) { buffer.putInt((int) new File(fileName).length()); }/*from w ww . j a va 2 s .c om*/ // put body do { buffer.flip(); foc.write(buffer); buffer.clear(); } while (fic.read(buffer) != -1); fic.close(); // NOTE: do not close 'foc' Files.delete(fileName); }