Java: reading strings from a random access file with buffered input

后端 未结 7 1812
醉话见心
醉话见心 2020-12-14 12:40

I\'ve never had close experiences with Java IO API before and I\'m really frustrated now. I find it hard to believe how strange and complex it is and how hard it could be to

相关标签:
7条回答
  • 2020-12-14 13:37

    For @Ken Bloom A very quick go at a Java 7 version. Note: I don't think this is the most efficient way, I'm still getting my head around NIO.2, Oracle has started their tutorial here

    Also note that this isn't using Java 7's new ARM syntax (which takes care of the Exception handling for file based resources), it wasn't working in the latest openJDK build that I have. But if people want to see the syntax, let me know.

    /* 
     * Paths uses the default file system, note no exception thrown at this stage if 
     * file is missing
     */
    Path file = Paths.get("C:/Projects/timesheet.txt");
    ByteBuffer readBuffer = ByteBuffer.allocate(readBufferSize);
    FileChannel fc = null;
    try
    {
        /*
         * newByteChannel is a SeekableByteChannel - this is the fun new construct that 
         * supports asynch file based I/O, e.g. If you declared an AsynchronousFileChannel 
         * you could read and write to that channel simultaneously with multiple threads.
         */
        fc = (FileChannel)file.newByteChannel(StandardOpenOption.READ);
        fc.position(startPosition);
        while (fc.read(readBuffer) != -1)
        {
            readBuffer.rewind();
            System.out.println(Charset.forName(encoding).decode(readBuffer));
            readBuffer.flip();
        }
    }
    
    0 讨论(0)
提交回复
热议问题