我的字节数组长度不等于文件 .txt 文件大小

My byte array length is not equal to the file .txt file size

所以基本上我想要做的是让 JProgressBar 从 0-100% 移动,其中 100% 是一个包含 9999 行单词的完全读取的 .txt 文件。

我试图通过将一个巨大的字符串分割成字节存储到一个字节数组中并用字节数组的长度更新 JPBar 来做到这一点。

令我惊讶的是,JProgressBar 停在了 91%。后来我决定打印出这些值并意识到文件长度比字节数组长度大 ~10000。

有人可以向我解释为什么会这样吗?我怎样才能做对呢?我意识到我很可能错过了关于阅读和计算字符的概念。代码片段如下。

谢谢!

bar.setMinimum(0);
bar.setMaximum((int)file.length());

try{
     while((check = reader.readLine()) != null){

         words = words + check + "\n";
         stringCount = words.getBytes();
         bar.setValue(stringCount.length);

     }      
  }catch(Exception e){}

  System.out.println(stringCount.length);
  System.out.println(file.length());

额外的文件内容很可能是 Windows 式行尾的其他部分。 Windows 上文件的标准行结尾是 \r\n,但您的内存中字符串仅包含 \n。这会在每行结尾累积 1 个字符的差异,并且 9999 行与您报告的差异相匹配。