0

This is the code I am using that retrieves data from a letter.txt file

File file = new File("/Users/Shiv/Eclipse/CPS3498/letter.txt");
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            StringBuffer stringBuffer = new StringBuffer();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
                stringBuffer.append("\n");
            }
            fileReader.close(); 

I am trying to put the contents of letter.txt into this.

        byte[] text = "No body can see me".getBytes();
Shiv
  • 1
  • 2

1 Answers1

0

This should do it:

File file = new File("/Users/Shiv/Eclipse/CPS3498/letter.txt");
final byte[] text;
FileInputStream fis = new FileInputStream(file);
try
{
    FileChannel fc = fis.getChannel();
    long size = fc.size();
    if (size > Integer.MAX_VALUE)
    {
        throw new IllegalStateException("File too large");
    }
    text = new byte[(int) size];
    fc.read(ByteBuffer.wrap(text));
}
finally
{
    fis.close();
}
System.out.println(text.length);
Glenn Lane
  • 3,892
  • 17
  • 31