List of usage examples for java.nio.channels FileChannel read
public final long read(ByteBuffer[] dsts) throws IOException
From source file:org.jasig.portlet.attachment.util.FileUtil.java
public static byte[] read(File file) throws IOException { if (file == null || !file.exists()) return null; if (locks.contains(file.getAbsolutePath())) { try {//w w w. ja va 2s . c o m Thread.sleep(100); } catch (InterruptedException ie) { } } FileInputStream input = null; try { input = new FileInputStream(file); int available = input.available(); FileChannel channel = input.getChannel(); ByteBuffer bytes = ByteBuffer.allocate(available); channel.read(bytes); bytes.flip(); return bytes.array(); } finally { if (input != null) { input.close(); } } }
From source file:org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.MappableBlock.java
/** * Reads bytes into a buffer until EOF or the buffer's limit is reached *//*from ww w .ja v a2s . co m*/ private static int fillBuffer(FileChannel channel, ByteBuffer buf) throws IOException { int bytesRead = channel.read(buf); if (bytesRead < 0) { //EOF return bytesRead; } while (buf.remaining() > 0) { int n = channel.read(buf); if (n < 0) { //EOF return bytesRead; } bytesRead += n; } return bytesRead; }
From source file:org.alfresco.repo.content.http.HttpAlfrescoStore.java
private static void doTest(ApplicationContext ctx, String baseUrl, String contentUrl) throws Exception { ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY); TransactionService transactionService = serviceRegistry.getTransactionService(); AuthenticationService authenticationService = serviceRegistry.getAuthenticationService(); // Construct the store HttpAlfrescoStore store = new HttpAlfrescoStore(); store.setTransactionService(transactionService); store.setAuthenticationService(authenticationService); store.setBaseHttpUrl(baseUrl);//w w w . j a va2s.c om // Now test System.out.println(" Retrieving reader for URL " + contentUrl); ContentReader reader = store.getReader(contentUrl); System.out.println(" Retrieved reader for URL " + contentUrl); // Check if the content exists boolean exists = reader.exists(); if (!exists) { System.out.println(" Content doesn't exist: " + contentUrl); return; } else { System.out.println(" Content exists: " + contentUrl); } // Get the content data ContentData contentData = reader.getContentData(); System.out.println(" Retrieved content data: " + contentData); // Now get the content ByteBuffer buffer = ByteBuffer.allocate((int) reader.getSize()); FileChannel channel = reader.getFileChannel(); try { int count = channel.read(buffer); if (count != reader.getSize()) { System.err.println("The number of bytes read was " + count + " but expected " + reader.getSize()); return; } } finally { channel.close(); } }
From source file:Main.java
public static String readString(String filePath) { File file = new File(filePath); if (!file.exists()) return null; FileInputStream fileInput = null; FileChannel channel = null; try {// ww w .j av a2 s. co m fileInput = new FileInputStream(filePath); channel = fileInput.getChannel(); ByteBuffer buffer = ByteBuffer.allocate((int) channel.size()); channel.read(buffer); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byteArrayOutputStream.write(buffer.array()); return byteArrayOutputStream.toString(); } catch (Exception e) { } finally { if (fileInput != null) { try { fileInput.close(); } catch (IOException e) { e.printStackTrace(); } } if (channel != null) { try { channel.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; }
From source file:com.log4ic.compressor.utils.FileUtils.java
/** * ?/* ww w . j a va2 s . c om*/ * * @param fileInputStream * @return */ public static String readFile(FileInputStream fileInputStream) throws IOException { ByteBuffer buffer = ByteBuffer.allocate(1024); StringBuffer contentBuffer = new StringBuffer(); Charset charset = null; CharsetDecoder decoder = null; CharBuffer charBuffer = null; try { FileChannel channel = fileInputStream.getChannel(); while (true) { buffer.clear(); int pos = channel.read(buffer); if (pos == -1) { break; } buffer.flip(); charset = Charset.forName("UTF-8"); decoder = charset.newDecoder(); charBuffer = decoder.decode(buffer); contentBuffer.append(charBuffer.toString()); } } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return contentBuffer.toString(); }
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 av a2 s . c om*/ 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:com.sunchenbin.store.feilong.core.io.IOReaderUtil.java
/** * ?.// w w w . java 2 s.co m * * @param file * * @param charsetName * ?,isNullOrEmpty, {@link CharsetType#UTF8} * @return the file content * @see org.apache.commons.io.FileUtils#readFileToString(File, Charset) */ public static String getFileContent(File file, String charsetName) { if (Validator.isNullOrEmpty(file)) { throw new NullPointerException("the file is null or empty!"); } // ? final int capacity = 186140; ByteBuffer byteBuffer = ByteBuffer.allocateDirect(capacity); StringBuilder sb = new StringBuilder(capacity); FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(file); // ?????. FileChannel fileChannel = fileInputStream.getChannel(); String useCharsetName = Validator.isNullOrEmpty(charsetName) ? DEFAULT_CHARSET_NAME : charsetName; Charset charset = Charset.forName(useCharsetName); while (fileChannel.read(byteBuffer) != -1) { // ?? byteBuffer.flip(); CharBuffer charBuffer = charset.decode(byteBuffer); sb.append(charBuffer.toString()); byteBuffer.clear(); } return sb.toString(); } catch (FileNotFoundException e) { throw new UncheckedIOException(e); } catch (IOException e) { throw new UncheckedIOException(e); } finally { // ? ,^_^ IOUtils.closeQuietly(fileInputStream); } }
From source file:yui.classes.utils.IOUtils.java
public static byte[] fileReadNIO(String name) { FileInputStream f = null;/*w w w .ja v a 2 s.c o m*/ ByteBuffer bb = null; try { f = new FileInputStream(name); FileChannel ch = f.getChannel(); bb = ByteBuffer.allocateDirect(1024); long checkSum = 0L; int nRead; while ((nRead = ch.read(bb)) != -1) { bb.position(0); bb.limit(nRead); while (bb.hasRemaining()) { checkSum += bb.get(); } bb.clear(); } } catch (FileNotFoundException ex) { logger.error(ex.getMessage()); } catch (IOException ex) { logger.error(ex.getMessage()); } finally { try { f.close(); } catch (IOException ex) { logger.error(ex.getMessage()); } } return bb.array(); }
From source file:com.ery.ertc.estorm.util.IOUtils.java
/** * Reads len bytes in a loop using the channel of the stream * //from w w w . ja v a 2s. co m * @param fileChannel * a FileChannel to read len bytes into buf * @param buf * The buffer to fill * @param off * offset from the buffer * @param len * the length of bytes to read * @throws IOException * if it could not read requested number of bytes for any reason * (including EOF) */ public static void readFileChannelFully(FileChannel fileChannel, byte buf[], int off, int len) throws IOException { int toRead = len; ByteBuffer byteBuffer = ByteBuffer.wrap(buf, off, len); while (toRead > 0) { int ret = fileChannel.read(byteBuffer); if (ret < 0) { throw new IOException("Premeture EOF from inputStream"); } toRead -= ret; off += ret; } }
From source file:com.turn.ttorrent.common.TorrentCreator.java
/** * Return the concatenation of the SHA-1 hashes of a file's pieces. * * <p>/* www.j a v a 2s. c o m*/ * Hashes the given file piece by piece using the default Torrent piece * length (see {@link #PIECE_LENGTH}) and returns the concatenation of * these hashes, as a string. * </p> * * <p> * This is used for creating Torrent meta-info structures from a file. * </p> * * @param file The file to hash. */ public /* for testing */ static byte[] hashFiles(Executor executor, List<File> files, long nbytes, int pieceLength) throws InterruptedException, IOException { int npieces = (int) Math.ceil((double) nbytes / pieceLength); byte[] out = new byte[Torrent.PIECE_HASH_SIZE * npieces]; CountDownLatch latch = new CountDownLatch(npieces); ByteBuffer buffer = ByteBuffer.allocate(pieceLength); long start = System.nanoTime(); int piece = 0; for (File file : files) { logger.info("Hashing data from {} ({} pieces)...", new Object[] { file.getName(), (int) Math.ceil((double) file.length() / pieceLength) }); FileInputStream fis = FileUtils.openInputStream(file); FileChannel channel = fis.getChannel(); int step = 10; try { while (channel.read(buffer) > 0) { if (buffer.remaining() == 0) { buffer.flip(); executor.execute(new ChunkHasher(out, piece, latch, buffer)); buffer = ByteBuffer.allocate(pieceLength); piece++; } if (channel.position() / (double) channel.size() * 100f > step) { logger.info(" ... {}% complete", step); step += 10; } } } finally { channel.close(); fis.close(); } } // Hash the last bit, if any if (buffer.position() > 0) { buffer.flip(); executor.execute(new ChunkHasher(out, piece, latch, buffer)); piece++; } // Wait for hashing tasks to complete. latch.await(); long elapsed = System.nanoTime() - start; logger.info("Hashed {} file(s) ({} bytes) in {} pieces ({} expected) in {}ms.", new Object[] { files.size(), nbytes, piece, npieces, String.format("%.1f", elapsed / 1e6) }); return out; }