List of usage examples for java.nio.channels FileChannel position
public abstract long position() throws IOException;
From source file:Main.java
public static void main(String[] args) throws IOException { int i = 0;//from ww w . j av a 2 s . co m FileInputStream fis = new FileInputStream("C://test.txt"); // read till the end of the file while ((i = fis.read()) != -1) { // get file channel FileChannel fc = fis.getChannel(); // get channel position long pos = fc.position(); char c = (char) i; System.out.println("No of bytes read: " + pos); System.out.println("Char read: " + c); } }
From source file:Main.java
public static void main(String[] args) throws IOException { byte b[] = { 65, 66, 67, 68, 69 }; FileOutputStream fos = new FileOutputStream("C://test.txt"); fos.write(b);/*from w w w . jav a 2 s .co m*/ // pushes stream content to the underlying file fos.flush(); // returns file channel associated with this stream FileChannel fc = fos.getChannel(); // returns the number of bytes written long pos = fc.position(); System.out.print(pos); }
From source file:MainClass.java
public static void main(String[] argv) throws IOException { RandomAccessFile randomAccessFile = new RandomAccessFile("test.dat", "r"); randomAccessFile.seek(1000);//from w w w. j a v a2s . c om FileChannel fileChannel = randomAccessFile.getChannel(); // This will print "1000" System.out.println("file pos: " + fileChannel.position()); randomAccessFile.seek(500); // This will print "500" System.out.println("file pos: " + fileChannel.position()); fileChannel.position(200); // This will print "200" System.out.println("file pos: " + randomAccessFile.getFilePointer()); }
From source file:Main.java
public static boolean fileCopy(File srcFile, File dstFile) { int length = 1048891; FileChannel inC = null; FileChannel outC = null;//from w ww . j a v a2s .co m try { FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(dstFile); inC = in.getChannel(); outC = out.getChannel(); ByteBuffer b = null; while (inC.position() < inC.size()) { if ((inC.size() - inC.position()) < length) { length = (int) (inC.size() - inC.position()); } else { length = 1048891; } b = ByteBuffer.allocateDirect(length); inC.read(b); b.flip(); outC.write(b); outC.force(false); } return true; } catch (IOException e) { e.printStackTrace(); return false; } finally { try { if (inC != null && inC.isOpen()) { inC.close(); } if (outC != null && outC.isOpen()) { outC.close(); } } catch (IOException e) { e.printStackTrace(); } } }
From source file:org.grouplens.lenskit.data.dao.packed.BinaryRatingDAO.java
/** * Open a binary rating DAO./*from ww w .j a v a 2s . c om*/ * @param file The file to open. * @return A DAO backed by {@code file}. * @throws IOException If there is */ public static BinaryRatingDAO open(File file) throws IOException { FileInputStream input = new FileInputStream(file); try { FileChannel channel = input.getChannel(); BinaryHeader header = BinaryHeader.read(channel); logger.info("Loading DAO with {} ratings of {} items from {} users", header.getRatingCount(), header.getItemCount(), header.getUserCount()); ByteBuffer data = channel.map(FileChannel.MapMode.READ_ONLY, channel.position(), header.getRatingDataSize()); channel.position(channel.position() + header.getRatingDataSize()); ByteBuffer tableBuffer = channel.map(FileChannel.MapMode.READ_ONLY, channel.position(), channel.size() - channel.position()); BinaryIndexTable utbl = BinaryIndexTable.fromBuffer(header.getUserCount(), tableBuffer); BinaryIndexTable itbl = BinaryIndexTable.fromBuffer(header.getItemCount(), tableBuffer); return new BinaryRatingDAO(file, header, data, utbl, itbl); } finally { input.close(); } }
From source file:org.solmix.commons.util.Files.java
/** * ?// w w w . ja va 2s. c o m * * @param f1 * ? * @param f2 * * @throws Exception */ public static void copyFile(File f1, File f2) throws Exception { int length = 2097152; FileInputStream in = new FileInputStream(f1); FileOutputStream out = new FileOutputStream(f2); FileChannel inC = in.getChannel(); FileChannel outC = out.getChannel(); ByteBuffer b = null; while (true) { if (inC.position() == inC.size()) { inC.close(); outC.close(); } if ((inC.size() - inC.position()) < length) { length = (int) (inC.size() - inC.position()); } else length = 2097152; b = ByteBuffer.allocateDirect(length); inC.read(b); b.flip(); outC.write(b); outC.force(false); } }
From source file:com.turn.ttorrent.common.TorrentCreator.java
/** * Return the concatenation of the SHA-1 hashes of a file's pieces. * * <p>/*from w ww . j a v a 2 s. 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; }
From source file:org.lenskit.data.packed.BinaryRatingDAO.java
/** * Open a binary rating DAO.//from ww w.ja v a2s . c om * * @param file The file to open. * @return A DAO backed by {@code file}. * @throws IOException If there is */ public static BinaryRatingDAO open(File file) throws IOException { try (FileInputStream input = new FileInputStream(file)) { FileChannel channel = input.getChannel(); BinaryHeader header = BinaryHeader.read(channel); logger.info("Loading DAO with {} ratings of {} items from {} users", header.getRatingCount(), header.getItemCount(), header.getUserCount()); // the channel position has been advanced to end of header ByteBuffer data = channel.map(FileChannel.MapMode.READ_ONLY, channel.position(), header.getRatingDataSize()); channel.position(channel.position() + header.getRatingDataSize()); ByteBuffer tableBuffer = channel.map(FileChannel.MapMode.READ_ONLY, channel.position(), channel.size() - channel.position()); BinaryIndexTable utbl = BinaryIndexTable.fromBuffer(header.getUserCount(), tableBuffer); BinaryIndexTable itbl = BinaryIndexTable.fromBuffer(header.getItemCount(), tableBuffer); return new BinaryRatingDAO(file, header, data, utbl, itbl, header.getRatingCount(), Long.MAX_VALUE); } }
From source file:me.carpela.network.pt.cracker.tools.ttorrent.Torrent.java
private static String hashFiles(List<File> files, int pieceLenght) throws InterruptedException, IOException, NoSuchAlgorithmException { int threads = getHashingThreadsCount(); ExecutorService executor = Executors.newFixedThreadPool(threads); ByteBuffer buffer = ByteBuffer.allocate(pieceLenght); List<Future<String>> results = new LinkedList<Future<String>>(); StringBuilder hashes = new StringBuilder(); long length = 0L; int pieces = 0; long start = System.nanoTime(); for (File file : files) { length += file.length();// w w w . j a v a2 s. c o m FileInputStream fis = new FileInputStream(file); FileChannel channel = fis.getChannel(); int step = 10; try { while (channel.read(buffer) > 0) { if (buffer.remaining() == 0) { buffer.clear(); results.add(executor.submit(new CallableChunkHasher(buffer))); } if (results.size() >= threads) { pieces += accumulateHashes(hashes, results); } if (channel.position() / (double) channel.size() * 100f > step) { step += 10; } } } finally { channel.close(); fis.close(); } } // Hash the last bit, if any if (buffer.position() > 0) { buffer.limit(buffer.position()); buffer.position(0); results.add(executor.submit(new CallableChunkHasher(buffer))); } pieces += accumulateHashes(hashes, results); // Request orderly executor shutdown and wait for hashing tasks to // complete. executor.shutdown(); while (!executor.isTerminated()) { Thread.sleep(10); } long elapsed = System.nanoTime() - start; int expectedPieces = (int) (Math.ceil((double) length / pieceLenght)); return hashes.toString(); }
From source file:org.cloudata.core.commitlog.FileTransferThread.java
private void transfer(FileChannel[] channelList, SocketChannel socketChannel) { for (FileChannel fc : channelList) { try {// w ww. j av a 2s . co m long numTransferred = 0; long pos = fc.position(); long totalLength = fc.size() - pos; long count = totalLength; LOG.info(dirName + " start File Transfer:" + pos + "," + totalLength); while ((numTransferred += fc.transferTo(pos, count, socketChannel)) < totalLength) { pos += numTransferred; count -= numTransferred; } //LOG.info("End File Transfer:" + pos + "," + totalLength); } catch (IOException e) { LOG.warn("transfering file is fail due to : ", e); } finally { if (fc != null) { try { fc.close(); } catch (IOException e) { LOG.warn("closing file is fail due to : ", e); } } } } }