Java loading binary files

前端 未结 2 742
太阳男子
太阳男子 2021-01-16 17:51

Please show me the best/fast methods for:

1) Loading very small binary files into memory. For example icons;

2) Loading/reading very big binary files of size

相关标签:
2条回答
  • 2021-01-16 18:30

    For memory mapped files, java has a nio package: Memory Mapped Files

    Check out byte stream class for small files:Byte Stream

    Check out buffered I/O for larger files: Buffered Stream

    0 讨论(0)
  • 2021-01-16 18:49

    The simplest way to read a small file into memory is:

    // Make a file object from the path name
    File file=new File("mypath");
    // Find the size
    int size=file.length();
    // Create a buffer big enough to hold the file
    byte[] contents=new byte[size];
    // Create an input stream from the file object
    FileInputStream in=new FileInutStream(file);
    // Read it all
    in.read(contents);
    // Close the file
    in.close();
    

    In real life you'd need some try/catch blocks in case of I/O errors.

    If you're reading a big file, I would strongly suggest NOT reading it all into memory at one time if it can possibly be avoided. Read it and process it in chunks. It's a very rare application that really needs to hold a 500MB file in memory all at once.

    There is no such thing as memory-mapped I/O in Java. If that's what you need to do, you'd just have to create a really big byte array.

    0 讨论(0)
提交回复
热议问题