需要帮助将文本文件导入到JDK 6的byte []中

时间:2016-09-30 20:26:00

标签: java encoding decode

这是我正在使用的代码,它从letter.txt文件中检索数据

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(); 

我正在尝试将letter.txt的内容放入此内容。

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

1 个答案:

答案 0 :(得分:0)

这应该这样做:

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);