JavascriptProva

domenica 20 marzo 2016

Leggere i bytes da un file

Ed ecco ora il FileInputStream per leggere i bytes di un file in un buffer:
public class MainActivity extends Activity {

 Button button;
 Button button2;
 Button button3;
 Button button4;

 String filePath = Environment.getExternalStorageDirectory()
   .getAbsolutePath() + "/ilmiofiledalnomelungolungo";

 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  button = (Button) findViewById(R.id.button1);
  button2 = (Button) findViewById(R.id.button2);
  button3 = (Button) findViewById(R.id.button3);
  button4 = (Button) findViewById(R.id.button4);

  button.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View v) {

    try {
     FileOutputStream fos = new FileOutputStream(filePath);
     byte[] nome = { 0x41, 0x4e, 0x54, 0x4f, 0x4e, 0x45, 0x4c,
       0x4c, 0x4f };
     fos.write(nome);
    } catch (Exception e) {
     e.printStackTrace();
    }

   }
  });
  button2.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View v) {
    try {
     FileInputStream fis=new FileInputStream(filePath);
     byte[] buffer=new byte[50];
     fis.read(buffer);
     for(int i=0;i<50;i++){
      Log.d(i+"",buffer[i]+"");
     }
    } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }

   }
  });
 }

}
Ecco il risultato in LogCat:
03-19 17:03:03.740: D/0(15493): 65
03-19 17:03:03.740: D/1(15493): 78
03-19 17:03:03.740: D/2(15493): 84
03-19 17:03:03.740: D/3(15493): 79
03-19 17:03:03.740: D/4(15493): 78
03-19 17:03:03.740: D/5(15493): 69
03-19 17:03:03.740: D/6(15493): 76
03-19 17:03:03.740: D/7(15493): 76
03-19 17:03:03.740: D/8(15493): 79
03-19 17:03:03.740: D/9(15493): 0
03-19 17:03:03.740: D/10(15493): 0
03-19 17:03:03.740: D/11(15493): 0
...che sono i codici ASCII di "ANTONELLO" in notazione decimale.
65/16= 4 con resto di 1: 0x41
78/16= 4 con resto di 14 (E): 0x4e
84/16= 5 con resto di 4; 0x54
79/16= 4 con resto di 15 (F): 0x4f
...eccetera...

E' valso la pena, imparare la tabellina del 16, per fare i calcoli un po' più agevolmente! :D

Nessun commento:

Posta un commento