Java Code Examples for java.io.FileInputStream.getChannel()

The following are Jave code examples for showing how to use getChannel() of the java.io.FileInputStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: hadoop   File: MappableBlock.java   View Source Code Vote up 6 votes
/**
 * Load the block.
 *
 * mmap and mlock the block, and then verify its checksum.
 *
 * @param length         The current length of the block.
 * @param blockIn        The block input stream.  Should be positioned at the
 *                       start.  The caller must close this.
 * @param metaIn         The meta file input stream.  Should be positioned at
 *                       the start.  The caller must close this.
 * @param blockFileName  The block file name, for logging purposes.
 *
 * @return               The Mappable block.
 */
public static MappableBlock load(long length,
    FileInputStream blockIn, FileInputStream metaIn,
    String blockFileName) throws IOException {
  MappableBlock mappableBlock = null;
  MappedByteBuffer mmap = null;
  FileChannel blockChannel = null;
  try {
    blockChannel = blockIn.getChannel();
    if (blockChannel == null) {
      throw new IOException("Block InputStream has no FileChannel.");
    }
    mmap = blockChannel.map(MapMode.READ_ONLY, 0, length);
    NativeIO.POSIX.getCacheManipulator().mlock(blockFileName, mmap, length);
    verifyChecksum(length, metaIn, blockChannel, blockFileName);
    mappableBlock = new MappableBlock(mmap, length);
  } finally {
    IOUtils.closeQuietly(blockChannel);
    if (mappableBlock == null) {
      if (mmap != null) {
        NativeIO.POSIX.munmap(mmap); // unmapping also unlocks
      }
    }
  }
  return mappableBlock;
}
 
Example 2
Project: Remindy   File: FileUtil.java   View Source Code Vote up 6 votes
/**
 * Creates the specified <code>toFile</code> as a byte for byte copy of the
 * <code>fromFile</code>. If <code>toFile</code> already exists, then it
 * will be replaced with a copy of <code>fromFile</code>. The name and path
 * of <code>toFile</code> will be that of <code>toFile</code>.<br/>
 * <br/>
 * <i> Note: <code>fromFile</code> and <code>toFile</code> will be closed by
 * this function.</i>
 *
 * @param fromFile
 *            - FileInputStream for the file to copy from.
 * @param toFile
 *            - FileInputStream for the file to copy to.
 */
public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
    FileChannel fromChannel = null;
    FileChannel toChannel = null;
    try {
        fromChannel = fromFile.getChannel();
        toChannel = toFile.getChannel();
        fromChannel.transferTo(0, fromChannel.size(), toChannel);
    } finally {
        try {
            if (fromChannel != null) {
                fromChannel.close();
            }
        } finally {
            if (toChannel != null) {
                toChannel.close();
            }
        }
    }
}
 
Example 3
Project: AirQuickUtils   File: AirSdcard.java   View Source Code Vote up 6 votes
/**
 * Creates the specified <code>toFile</code> as a byte for byte copy of the
 * <code>fromFile</code>. If <code>toFile</code> already exists, then it
 * will be replaced with a copy of <code>fromFile</code>. The name and path
 * of <code>toFile</code> will be that of <code>toFile</code>.<br/>
 * <br/>
 * <i> Note: <code>fromFile</code> and <code>toFile</code> will be closed by
 * this function.</i>
 *
 * @param fromFile - FileInputStream for the file to copy from.
 * @param toFile   - FileOutpubStream for the file to copy to.
 */
public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
    FileChannel fromChannel = null;
    FileChannel toChannel = null;
    try {
        fromChannel = fromFile.getChannel();
        toChannel = toFile.getChannel();
        fromChannel.transferTo(0, fromChannel.size(), toChannel);
    } finally {
        try {
            if (fromChannel != null) {
                fromChannel.close();
            }
        } finally {
            if (toChannel != null) {
                toChannel.close();
            }
        }
    }
}
 
Example 4
Project: jaer   File: MotionInputStream.java   View Source Code Vote up 6 votes
private void init(FileInputStream is) {
        fileInputStream=is;
        fileChannel=is.getChannel();
        try{
            fileSize=fileChannel.size();
        }catch(IOException e){
            e.printStackTrace();
            fileSize=0;
        }
        boolean openok=false;
//        reader=new InputStreamReader(fileInputStream);
//
//        try{
//            readHeader();
//        }catch(IOException e){
//            log.warning("couldn't read header");
//        }
        size=fileSize/motionData.getLoggedObjectSize();
        dataInputStream=new DataInputStream(Channels.newInputStream(fileChannel));
        getSupport().firePropertyChange("position",0,position());
        position(1);

    }
 
Example 5
Project: aos-FileCoreLibrary   File: ArchosFileChannel.java   View Source Code Vote up 6 votes
static public long transfer(long position, long count, FileInputStream src, FileOutputStream dst) throws IOException {
    FileChannel srcChannel = src.getChannel();
    FileChannel dstChannel = dst.getChannel();
    if (!srcChannel.isOpen()) {
        throw new ClosedChannelException();
    }
    if (!dstChannel.isOpen()) {
        throw new ClosedChannelException();
    }

    if (position < 0 || count < 0) {
        throw new IllegalArgumentException("position=" + position + " count=" + count);
    }

    if (count == 0 || position >= srcChannel.size()) {
        return 0;
    }
    count = Math.min(count, srcChannel.size() - position);

    FileDescriptor inFd = src.getFD();
    FileDescriptor outFd = dst.getFD();
    long rc = 0;
    rc = native_sendfile_64(outFd, inFd, position, count);
    return rc;
}
 
Example 6
Project: CatchSpy   File: Code.java   View Source Code Vote up 5 votes
public static String getFileMD5String(String path) {
    try {
        File file = new File(path);
        FileInputStream in = new FileInputStream(file);
        FileChannel ch = in.getChannel();
        MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.update(byteBuffer);
        return bufferToHex(messageDigest.digest());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 7
Project: EatDubbo   File: Logs.java   View Source Code Vote up 5 votes
public void index(Map<String, Object> context) throws Exception {
    long size;
    String content;
    String modified;
    File file = LoggerFactory.getFile();
    if (file != null && file.exists()) {
        FileInputStream fis = new FileInputStream(file);
        FileChannel channel = fis.getChannel();
        size = channel.size();
        ByteBuffer bb;
        if (size <= SHOW_LOG_LENGTH) {
            bb = ByteBuffer.allocate((int) size);
            channel.read(bb, 0);
        } else {
            int pos = (int) (size - SHOW_LOG_LENGTH);
            bb = ByteBuffer.allocate(SHOW_LOG_LENGTH);
            channel.read(bb, pos);
        }
        bb.flip();
        content = new String(bb.array()).replace("<", "&lt;").replace(">", "&gt;");
        modified = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(file.lastModified()));
    } else {
        size = 0;
        content = "";
        modified = "Not exist";
    }
    Level level = LoggerFactory.getLevel();
    context.put("name", file == null ? "" : file.getAbsoluteFile());
    context.put("size", String.valueOf(size));
    context.put("level", level == null ? "" : level);
    context.put("modified", modified);
    context.put("content", content);
}
 
Example 8
Project: ibm-cos-sdk-java   File: ResettableInputStream.java   View Source Code Vote up 5 votes
/**
 * @param file
 *            can be null if not known
 */
private ResettableInputStream(FileInputStream fis, File file) throws IOException {
    super(fis);
    this.file = file;
    this.fis = fis;
    this.fileChannel = fis.getChannel();
    this.markPos = fileChannel.position();
}
 
Example 9
Project: AndiCar   File: FileUtils.java   View Source Code Vote up 5 votes
/**
     * copy a file
     *
     * @param source source file
     * @param dest   destination file
     * @return null on success; error message on failure
     */
    private static String copyFile(Context ctx, File source, File dest) {

//        if (ContextCompat.checkSelfPermission(ctx, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
        if (!FileUtils.isFileSystemAccessGranted(ctx)) {
            return mResources.getString(R.string.error_102);
        }

        FileChannel in;
        FileChannel out;
        try {
            FileInputStream fileInputStream = new FileInputStream(source);
            in = fileInputStream.getChannel();
            FileOutputStream fileOutputStream = new FileOutputStream(dest);
            out = fileOutputStream.getChannel();

            long size = in.size();
            MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);

            out.write(buf);

            fileInputStream.close();
            fileOutputStream.close();
            in.close();
            out.close();
        }
        catch (IOException e) {
//            Toast toast = Toast.makeText(ctx, "Error: " + e.getMessage(), Toast.LENGTH_LONG);
//            toast.show();
            mLastException = e;
            mLastErrorMessage = e.getMessage();
            return e.getMessage();
        }
        return null;
    }
 
Example 10
Project: incubator-netbeans   File: BufferedCharSequenceTest.java   View Source Code Vote up 5 votes
/**
 * Returns {@code FileChennel} for the specified data file located in the
 * {@code org.netbeans.modules.search.data} package.
 * @param fileName - name of the data file.
 * @return {@code FileChennel} of the data file.
 */
public FileChannel getDataFileChannel(String fileName) {
    File file = getFile(fileName);

    FileInputStream fis = getFileInputStream(file);
    return fis.getChannel();
}
 
Example 11
Project: V8LogScanner   File: RgxReader.java   View Source Code Vote up 5 votes
public RgxReader(String fileName, Charset charset, int _limit) throws FileNotFoundException {

        this(CharBuffer.allocate(1024));

        fs = new FileInputStream(fileName);
        ReadableByteChannel channel = fs.getChannel();
        CharsetDecoder decoder = charset.newDecoder();
        reader = Channels.newReader(channel, decoder, -1);
        buf.limit(0);
        limit = _limit;
    }
 
Example 12
Project: OutsourcedProject   File: FileManagementUtil.java   View Source Code Vote up 5 votes
/**
 * @description 文件下载 nio 大缓存
 * @param response
 * @param file
 * @throws IOException
 */
public static void exportFileByNIO(HttpServletResponse response, File file) throws IOException {
    String filename = URLEncoder.encode(file.getName(), CharEncoding.UTF_8);
    response.setContentType(HttpUtil.CONTENT_TYPE_APPLICATION_OCTET_STREAM);
    response.setContentLength((int) file.length());
    response.setHeader(HttpUtil.CONTENT_DISPOSITION, "attachment;filename=" + filename);
    response.setHeader(HttpUtil.LOCATION, filename);
    ServletOutputStream op = response.getOutputStream();
    int bufferSize = 1024 * 128;
    FileInputStream fileInputStream = new FileInputStream(file.getPath());
    FileChannel fileChannel = fileInputStream.getChannel();
    ByteBuffer bb = ByteBuffer.allocateDirect(1024 * 1024 * 128);
    byte[] buffer = new byte[bufferSize];
    int nRead, nGet;
    while ((nRead = fileChannel.read(bb)) != -1) {
        if (nRead == 0) {
            continue;
        }
        bb.position(0);
        bb.limit(nRead);
        while (bb.hasRemaining()) {
            nGet = Math.min(bb.remaining(), bufferSize);
            bb.get(buffer, 0, nGet);
            op.write(buffer);
        }
        bb.clear();
    }
    fileChannel.close();
    fileInputStream.close();
}
 
Example 13
Project: BIMplatform   File: GlbToB3dmConvertor.java   View Source Code Vote up 5 votes
@SuppressWarnings("resource")
public ByteBuffer getBufferFromUri(String uri, Path containingFolder) throws IOException {
	// 2.0以后只在外部存储bin文件
	Path binPath = containingFolder.resolve(uri);
	FileInputStream fis = new FileInputStream(binPath.toFile());
	FileChannel channel = fis.getChannel();
	ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
	channel.read(byteBuffer);
	return byteBuffer;
}
 
Example 14
Project: UaicNlpToolkit   File: POStrainer.java   View Source Code Vote up 5 votes
static ObjectStream<POSSample> openSampleData(String sampleDataName, File sampleDataFile, Charset encoding) {
    CmdLineUtil.checkInputFile(sampleDataName + " Data", sampleDataFile);
    FileInputStream sampleDataIn = CmdLineUtil.openInFile(sampleDataFile);
    ObjectStream<String> lineStream = new PlainTextByLineStream(sampleDataIn.getChannel(), encoding);
    return new WordTagSampleStream(lineStream);
}
 
Example 15
Project: Android-Practice   File: MainActivity.java   View Source Code Vote up 4 votes
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ArrayList<String> arData = new ArrayList<String>();
    mAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, arData);
    ListView list = (ListView)findViewById(R.id.logList);
    mAdapter.add("ssss");
    list.setAdapter(mAdapter);

    try {
        FileInputStream fis = openFileInput("MousePos.txt");
        FileChannel inChannel = fis.getChannel();

        final int s = fis.available();
        ByteBuffer buff = ByteBuffer.allocate((int)fis.available());
        buff.clear();

        inChannel.read(buff);

        buff.rewind();

        final int posSize = s/4;
        float[] pos = new float[posSize];
        buff.asFloatBuffer().get(pos);

        inChannel.close();

        for (int i=0; i < posSize; i+=2)
        {
            mAdapter.add("" + pos[i] + ", " + pos[i+1]);
        }

        fis.close();
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }

    list.setOnTouchListener(this);
}
 
Example 16
Project: incubator-netbeans   File: AsciiMultiLineMappedMatcher.java   View Source Code Vote up 4 votes
@Override
protected Def checkMeasuredInternal(FileObject fo,
        SearchListener listener) {

    MappedByteBuffer bb = null;
    FileChannel fc = null;
    try {

        listener.fileContentMatchingStarted(fo.getPath());
        File file = FileUtil.toFile(fo);

        // Open the file and then get a channel from the stream
        FileInputStream fis = new FileInputStream(file);
        fc = fis.getChannel();

        // Get the file's size and then map it into memory
        int sz = (int) fc.size();
        bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);

        List<TextDetail> list = matchWholeFile(new FastCharSequence(bb, 0),
                fo);

        if (list != null && !list.isEmpty()) {
            return new Def(fo, Charset.forName("ASCII"), list);
        } else {
            return null;
        }
    } catch (Exception e) {
        listener.generalError(e);
        return null;
    } finally {
        if (fc != null) {
            try {
                fc.close();
            } catch (IOException ex) {
                listener.generalError(ex);
            }
        }
        MatcherUtils.unmap(bb);
    }
}
 
Example 17
Project: incubator-netbeans   File: FastMatcher.java   View Source Code Vote up 4 votes
/**
 * Check file content using Java NIO API.
 */
private Def checkSmall(FileObject fo, File file,
        SearchListener listener) {

    MappedByteBuffer bb = null;
    FileChannel fc = null;
    try {
        // Open the file and then get a channel from the stream
        FileInputStream fis = new FileInputStream(file);
        fc = fis.getChannel();

        // Get the file's size and then map it into memory
        int sz = (int) fc.size();
        bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);

        if (asciiPattern && !matchesIgnoringEncoding(bb)) {
            return null;
        }
        // Decode the file into a char buffer
        Charset charset = FileEncodingQuery.getEncoding(fo);
        CharsetDecoder decoder = prepareDecoder(charset);
        decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
        CharBuffer cb = decoder.decode(bb);

        List<TextDetail> textDetails = multiline
                ? matchWholeFile(cb, fo)
                : matchLines(cb, fo);
        if (textDetails == null) {
            return null;
        } else {
            Def def = new Def(fo, decoder.charset(), textDetails);
            return def;
        }
    } catch (Exception e) {
        listener.generalError(e);
        return null;
    } finally {
        if (fc != null) {
            try {
                fc.close();
            } catch (IOException ex) {
                listener.generalError(ex);
            }
        }
        unmap(bb);
    }
}
 
Example 18
Project: dubbo2   File: LogTelnetHandler.java   View Source Code Vote up 4 votes
public String telnet(Channel channel, String message) {
    long size = 0 ;
    File file = LoggerFactory.getFile();
    StringBuffer buf = new StringBuffer();
    if (message == null || message.trim().length() == 0) {
        buf.append("EXAMPLE: log error / log 100");
    }else {
        String str[] = message.split(" ");
        if (! StringUtils.isInteger(str[0])){
            LoggerFactory.setLevel(Level.valueOf(message.toUpperCase()));
        } else {
            int SHOW_LOG_LENGTH = Integer.parseInt(str[0]);
            
            if (file != null && file.exists()) {
                try{
                    FileInputStream fis = new FileInputStream(file);
                    try {
                     FileChannel filechannel = fis.getChannel();
                     try {
                      size = filechannel.size();
                      ByteBuffer bb;
                      if (size <= SHOW_LOG_LENGTH) {
                          bb = ByteBuffer.allocate((int) size);
                          filechannel.read(bb, 0);
                      } else {
                          int pos = (int) (size - SHOW_LOG_LENGTH);
                          bb = ByteBuffer.allocate(SHOW_LOG_LENGTH);
                          filechannel.read(bb, pos);
                      }
                      bb.flip();
                      String content = new String(bb.array()).replace("<", "&lt;")
                      .replace(">", "&gt;").replace("\n", "<br/><br/>");
                      buf.append("\r\ncontent:"+content);
                      
                      buf.append("\r\nmodified:"+(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                      .format(new Date(file.lastModified()))));
                      buf.append("\r\nsize:"+size +"\r\n");
                     } finally {
                     	filechannel.close();
                     }
                    } finally {
                    	fis.close();
                    }
                }catch (Exception e) {
                    buf.append(e.getMessage());
                }
            }else {
                size = 0;
                buf.append("\r\nMESSAGE: log file not exists or log appender is console .");
            }
        }
    }
    buf.append("\r\nCURRENT LOG LEVEL:"+ LoggerFactory.getLevel())
    .append("\r\nCURRENT LOG APPENDER:"+ (file == null ? "console" : file.getAbsolutePath()));
    return buf.toString();
}
 
Example 19
Project: dubbox-hystrix   File: LogTelnetHandler.java   View Source Code Vote up 4 votes
public String telnet(Channel channel, String message) {
    long size = 0 ;
    File file = LoggerFactory.getFile();
    StringBuffer buf = new StringBuffer();
    if (message == null || message.trim().length() == 0) {
        buf.append("EXAMPLE: log error / log 100");
    }else {
        String str[] = message.split(" ");
        if (! StringUtils.isInteger(str[0])){
            LoggerFactory.setLevel(Level.valueOf(message.toUpperCase()));
        } else {
            int SHOW_LOG_LENGTH = Integer.parseInt(str[0]);
            
            if (file != null && file.exists()) {
                try{
                    FileInputStream fis = new FileInputStream(file);
                    try {
                     FileChannel filechannel = fis.getChannel();
                     try {
                      size = filechannel.size();
                      ByteBuffer bb;
                      if (size <= SHOW_LOG_LENGTH) {
                          bb = ByteBuffer.allocate((int) size);
                          filechannel.read(bb, 0);
                      } else {
                          int pos = (int) (size - SHOW_LOG_LENGTH);
                          bb = ByteBuffer.allocate(SHOW_LOG_LENGTH);
                          filechannel.read(bb, pos);
                      }
                      bb.flip();
                      String content = new String(bb.array()).replace("<", "&lt;")
                      .replace(">", "&gt;").replace("\n", "<br/><br/>");
                      buf.append("\r\ncontent:"+content);
                      
                      buf.append("\r\nmodified:"+(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                      .format(new Date(file.lastModified()))));
                      buf.append("\r\nsize:"+size +"\r\n");
                     } finally {
                     	filechannel.close();
                     }
                    } finally {
                    	fis.close();
                    }
                }catch (Exception e) {
                    buf.append(e.getMessage());
                }
            }else {
                size = 0;
                buf.append("\r\nMESSAGE: log file not exists or log appender is console .");
            }
        }
    }
    buf.append("\r\nCURRENT LOG LEVEL:"+ LoggerFactory.getLevel())
    .append("\r\nCURRENT LOG APPENDER:"+ (file == null ? "console" : file.getAbsolutePath()));
    return buf.toString();
}
 
Example 20
Project: FreeStreams-TVLauncher   File: MD5Util.java   View Source Code Vote up 3 votes
/**
 * JDK1.4中不支持以MappedByteBuffer类型为参数update方法,并且网上有讨论要慎用MappedByteBuffer,
 * 原因是当使用 FileChannel.map 方法时,MappedByteBuffer 已经在系统内占用了一个句柄, 而使用
 * FileChannel.close 方法是无法释放这个句柄的,且FileChannel有没有提供类似 unmap 的方法,
 * 因此会出现无法删除文件的情况。
 *
 * 不推荐使用
 *
 * @param file
 * @return
 * @throws java.io.IOException
 */
public static String getFileMD5String_old(File file) throws IOException {
	FileInputStream in = new FileInputStream(file);
	FileChannel ch = in.getChannel();
	MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0,
			file.length());
	messagedigest.update(byteBuffer);
	return bufferToHex(messagedigest.digest());
}