2

I am writing a file in java with BufferedWriter. Here is my code -

public static void main(String[] args) {
    try(BufferedWriter writer = Files.newBufferedWriter(filePath, Charset.forName("CP1252"))) {
        while (thereIsContentToWrite){
            writer.write(content);
        }
    }catch (CharacterCodingException ce){
        //get content of writer's current buffer (java.io.BufferedWriter.cb)
    }catch (IOException e) {
        e.printStackTrace();
    }
}

I want to report out the content of the current buffer of writer as it contains the "Unmappable character" as per cp1252. Currently, we are trying to maintain another buffer to hold the content but I would like to know whether there is a better approach to achieve the same.

2 Answers2

1

If I understand correctly, you want to report the contents of the BufferedWriter buffer. You can do that, using the Reflection API.

The following code should retrieve the buffer contents:

// BufferedWriter buffer is the private field "cb"
Field bufferField = writer.getClass().getDeclaredField("cb");
// We make this field accessible so we can retrieve its contents
bufferField .setAccessible(true);
// We can now get the data
char[] buffer = (char[]) bufferField.get(writer);
HaroldH
  • 533
  • 1
  • 4
  • 10
  • Yeah, this is one of the approaches for sure! Thanks for replying. However, using reflection for other APIs is a little bit tricky. – Gandhali Ambike Dec 29 '17 at 06:57
1

You can write a CustomBufferedWriter which is similar to BufferedWriter and add a getter for cb in your implementation.

eatSleepCode
  • 4,427
  • 7
  • 44
  • 93