Domanda

I am trying to solve this problem.

open a binary file and prints all ASCII characters from that file, that is, all bytes with values between 32 and 126. Print a new line after every 64 characters

I came up with this code --

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

I would like to know if my approach is correct.

È stato utile?

Soluzione

Try This Way it worked for me.

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

}  
}

What happening in your code if(number or letter) than append , else if (check count)

While we want if(number or letter) than check is count==64 than append \n.

You can see the difference.

I hope you got your answer.

Best Of Luck

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top