Java nio close AsynchronousFileChannel after all operations are finished

Viewed 13

I'm building a Java library to read/write .csv files. I recently switched to using nio AsynchronousFileChannel for performing read and write operations. The problem is the channel reads only a small amount of text before closing itself because of try-with-resources. My question is how can I handle closing the file channel and making sure everything is read.

public List<String[]> readAllRecords() {
        // Detect encoding if there is none specified
        if (encoding == null) {
            encoding = CSVUtils.detectEncoding(filePath);
        }

        // List that will get returned in the end
        List<String[]> returnList = new ArrayList<>();

        // Create a file channel
        try (AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(filePath, StandardOpenOption.READ)) {
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            Future<Integer> operation = fileChannel.read(buffer, 0);
            
            // Other code runs
            operation.get();
            
            // Get the file content
            String fileContent = new String(buffer.array()).trim();
            buffer.clear();
            
            // Split the file content into lines
            String[] lines = fileContent.split("\\r?\\n");
            
            // Cycle through all lines
            for(String line : lines) {
                returnList.add(line.split(delimiter));
            }
            
            return returnList;
        } catch (Exception e) {
            logger.log(System.Logger.Level.ERROR, "Failed reading all records of file!", e);
        }

        return null;
    }
1 Answers

how about use while(!operation.isDone());

Related