giovedì 14 giugno 2012

Leggere e scrivere da file anche con caratteri cirillici su app android

In una mia app volevo leggere o inserire dati utilizzando anche il carattere cirillico (caratteri russi per intenderci).
Ahihahihahi quanto ho penato, ma alla fine è andata.
Di seguito lascio gli script che ho utilizzato:
Codice per la lettura:

StringBuilder text = new StringBuilder() ;
try { 
 FileInputStream fis = openFileInput("example.txt");
 BufferedReader br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
 String line="";    
 while ((line = br.readLine()) != null) {  
  text.append(line);   
  text.append('\n');    
 }
 br.close();
} catch (FileNotFoundException e) {
 //...
} 
catch (IOException e) {
 //...
} 
 
Codice per la scrittura:
try{
 String sdCard = Environment.getExternalStorageDirectory().toString();
 File file = new File(sdCard, "example.txt");
 FileOutputStream fosCard;

 if(file.exists())
  fosCard = new FileOutputStream(file,false);
 else
  fosCard = new FileOutputStream(file);
 Writer out = new BufferedWriter(new OutputStreamWriter(fosCard, "UTF-8"));
 List<? extends Map<String,?>> listDataCard = createItems(idTypeBook);
 for (Map<String, ?> map : listDataCard) {
  Book book = createItemBook((String)map.get(ID_KEY));
  out.append(createItemBookForFile(book).toString());//scrittura sul file
 }
 out.flush();
 out.close();
}
catch (FileNotFoundException e) {
 //...
}
catch (java.io.IOException e) {
 //...
}