【问题标题】:open a binary file and prints all ASCII characters from that file打开一个二进制文件并打印该文件中的所有 ASCII 字符
【发布时间】:2014-04-29 19:21:14
【问题描述】:

我正在努力解决这个问题。

打开一个二进制文件并打印其中的所有 ASCII 字符 文件,即值在 32 和 126 之间的所有字节。每 64 后打印一个新行 字符

我想出了这段代码--

public String asciiRead()
 throws IOException
{
 FileInputStream fis = null; 
 try {
  fis = new FileInputStream(fileName);
  int dataByte = 0;
  int count = 0;

  StringBuilder sb = new StringBuilder();

  while (-1 != (dataByte = fis.read())) {
   if (32 <= dataByte && dataByte <= 126) {
     sb.append((char) dataByte);
   }  else if (0 == (count % 64)) {
     sb.append("\n");
   }
   count++;
  }

 } finally {
   if (null != fis) { fis.close(); }
 }
 return sb.toString();
}

我想知道我的方法是否正确。

【问题讨论】:

  • 为什么不运行它并找出答案?
  • 您检查的是
  • 我运行这个......因为我没有太多使用 java 库的经验,所以请求审查这个。
  • @TeTeT - 我已经编辑过了..
  • 为什么使用else if?仅当读取的字节不是 ASCII 字符时,才会执行此块。据我了解,您想在每 64 个字符后添加一个换行符。另外,您的意思是“读取 64 个字符后”还是“读取 64 个 ASCII 字符后”?

标签: java file binary ascii


【解决方案1】:

试试这种方式它对我有用。

while ((dataByte = fis.read())!=-1) {
if (32 <= dataByte && dataByte <= 126 )
{
   count++;
sb.append((char) dataByte);
if (0 == (count % 64)) {
sb.append("\n");count=0;
}

}  
}

你的代码中发生了什么if(number or letter) than append , else if (check count)

虽然我们想要if(number or letter) than check is count==64 than append \n

你可以看到区别。

希望你能得到答案。

祝你好运

【讨论】:

  • else 必须被删除,否则每 64 个字符就会丢失一个字符。 dataByte 必须始终附加。
  • count 需要在外部 if 块内递增,然后再检查模 64。否则,如果每 64 个字符恰好不是 ASCII 字符,您可能最终没有换行。
  • 差不多了 :) 删除 else 块(包括 count++)并将第一个 count++ 移到第二个 if 之前。现在的方式是,在第 65 个字节而不是第 64 个 ASCII 字符之后添加一个新行。
猜你喜欢
  • 1970-01-01
  • 2017-02-02
  • 2015-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多