2010-11-03 12 views
95

Les choses sont simples mais ne fonctionnent pas comme prévu.Android lire le fichier de ressources brutes de texte

J'ai un fichier texte ajouté en tant que ressource brute. Le fichier texte contient du texte comme:

b) SI LA LOI EXIGE TOUTE GARANTIE EN CE QUI CONCERNE LE LOGICIEL , TOUTES CES GARANTIES SONT LIMITÉE À UNE DURÉE DE VINGT-DIX (90) JOURS DE LA DATE DE LIVRAISON .

(c) NO informations orales ou écrites OU CONSEIL DONNE PAR ORIENTATION VIRTUELLE, ses distributeurs, DISTRIBUTEURS, AGENTS OU COLLABORATEURS NE CONSTITUE UNE GARANTIE OU AUGMENTER LA PORTEE DE LA GARANTIE CONTENUE DANS .

(d) (États-Unis uniquement) CERTAINS ÉTATS NE PERMETTENT PAS L'EXCLUSION DE GARANTIE IMPLICITE , L'EXCLUSION CI-DESSUS PEUT NE PAS VOUS. CETTE GARANTIE DONNE VOUS DROITS LÉGAUX SPÉCIFIQUES ET VOUS POUVEZ AUSSI AVOIR D'AUTRES DROITS LÉGAUX QUE VARIENT D'UN ÉTAT À L'AUTRE.

Sur mon écran, j'ai une mise en page comme ceci:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:gravity="center" 
        android:layout_weight="1.0" 
        android:layout_below="@+id/logoLayout" 
        android:background="@drawable/list_background"> 

      <ScrollView android:layout_width="fill_parent" 
         android:layout_height="fill_parent"> 

        <TextView android:id="@+id/txtRawResource" 
           android:layout_width="fill_parent" 
           android:layout_height="fill_parent" 
           android:padding="3dip"/> 
      </ScrollView> 

    </LinearLayout> 

Le code pour lire la ressource brute est:

TextView txtRawResource= (TextView)findViewById(R.id.txtRawResource); 

txtDisclaimer.setText(Utils.readRawTextFile(ctx, R.raw.rawtextsample); 

public static String readRawTextFile(Context ctx, int resId) 
{ 
    InputStream inputStream = ctx.getResources().openRawResource(resId); 

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 

    int i; 
    try { 
     i = inputStream.read(); 
     while (i != -1) 
     { 
      byteArrayOutputStream.write(i); 
      i = inputStream.read(); 
     } 
     inputStream.close(); 
    } catch (IOException e) { 
     return null; 
    } 
    return byteArrayOutputStream.toString(); 
} 

Le texte get a montré, mais après chaque ligne je reçois un personnage étrange [] Comment puis-je supprimer ce personnage? Je pense que c'est New Line.

SOLUTION DE TRAVAIL

public static String readRawTextFile(Context ctx, int resId) 
{ 
    InputStream inputStream = ctx.getResources().openRawResource(resId); 

    InputStreamReader inputreader = new InputStreamReader(inputStream); 
    BufferedReader buffreader = new BufferedReader(inputreader); 
    String line; 
    StringBuilder text = new StringBuilder(); 

    try { 
     while ((line = buffreader.readLine()) != null) { 
      text.append(line); 
      text.append('\n'); 
     } 
    } catch (IOException e) { 
     return null; 
    } 
    return text.toString(); 
} 

Répondre

54

si vous utilisez un BufferedReader à base de caractères au lieu de InputStream à base d'octets?

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); 
String line = reader.readLine(); 
while (line != null) { ... } 

N'oubliez pas que readLine() ignore les nouvelles lignes!

140

Vous pouvez utiliser ceci:

try { 
     Resources res = getResources(); 
     InputStream in_s = res.openRawResource(R.raw.help); 

     byte[] b = new byte[in_s.available()]; 
     in_s.read(b); 
     txtHelp.setText(new String(b)); 
    } catch (Exception e) { 
     // e.printStackTrace(); 
     txtHelp.setText("Error: can't show help."); 
    } 
+4

Je ne suis pas sûr que le Inputstream.available() est le bon choix ici, lisez plutôt à un n ByteArrayOutputStream jusqu'au n == -1. – ThomasRS

+12

Cela peut ne pas fonctionner pour les ressources volumineuses. Cela dépend de la taille du tampon de lecture inputtream et ne peut renvoyer qu'une partie de la ressource. – d4n3

+4

@ d4n3 a raison, la documentation de la méthode de flux d'entrée disponible indique: "Renvoie un nombre estimé d'octets pouvant être lues ou ignorés sans bloquer pour plus d'entrées Notez que cette méthode fournit une garantie si faible qu'elle n'est pas très utile dans la pratique " – ozba

2

C'est une autre méthode qui va certainement travailler, mais je ne peux pas l'obtenir à lire plusieurs fichiers texte à afficher dans plusieurs textviews en une seule activité, quelqu'un peut aider?

TextView helloTxt = (TextView)findViewById(R.id.yourTextView); 
    helloTxt.setText(readTxt()); 
} 

private String readTxt(){ 

InputStream inputStream = getResources().openRawResource(R.raw.yourTextFile); 
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 

int i; 
try { 
i = inputStream.read(); 
while (i != -1) 
    { 
    byteArrayOutputStream.write(i); 
    i = inputStream.read(); 
    } 
    inputStream.close(); 
} catch (IOException e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 
} 

return byteArrayOutputStream.toString(); 
} 
1

@borislemke vous pouvez le faire en même manière comme

TextView tv ; 
findViewById(R.id.idOfTextView); 
tv.setText(readNewTxt()); 
private String readNewTxt(){ 
InputStream inputStream = getResources().openRawResource(R.raw.yourNewTextFile); 
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 

int i; 
try { 
i = inputStream.read(); 
while (i != -1) 
    { 
    byteArrayOutputStream.write(i); 
    i = inputStream.read(); 
    } 
    inputStream.close(); 
    } catch (IOException e) { 
    // TODO Auto-generated catch block 
e.printStackTrace(); 
} 

return byteArrayOutputStream.toString(); 
} 
24

Si vous utilisez IOUtils de "commons-io" apache il est encore plus facile:

InputStream is = getResources().openRawResource(R.raw.yourNewTextFile); 
String s = IOUtils.toString(is); 
IOUtils.closeQuietly(is); // don't forget to close your streams 

dépendances : http://mvnrepository.com/artifact/commons-io/commons-io

Maven:

<dependency> 
    <groupId>commons-io</groupId> 
    <artifactId>commons-io</artifactId> 
    <version>2.4</version> 
</dependency> 

Gradle:

'commons-io:commons-io:2.4' 
+0

Que devrais-je importer pour utiliser IOUtils? –

+1

Bibliothèque Apache commons-io (http://commons.apache.org/proper/commons-io/). Ou si vous utilisez Maven (http://mvnrepository.com/artifact/commons-io/commons-io). – tbraun

+6

Pour gradle: compile "commons-io: commons-io: 2.1" – JustinMorris

3

font plutôt cette façon:

// reads resources regardless of their size 
public byte[] getResource(int id, Context context) throws IOException { 
    Resources resources = context.getResources(); 
    InputStream is = resources.openRawResource(id); 

    ByteArrayOutputStream bout = new ByteArrayOutputStream(); 

    byte[] readBuffer = new byte[4 * 1024]; 

    try { 
     int read; 
     do { 
      read = is.read(readBuffer, 0, readBuffer.length); 
      if(read == -1) { 
       break; 
      } 
      bout.write(readBuffer, 0, read); 
     } while(true); 

     return bout.toByteArray(); 
    } finally { 
     is.close(); 
    } 
} 

    // reads a string resource 
public String getStringResource(int id, Charset encoding) throws IOException { 
    return new String(getResource(id, getContext()), encoding); 
} 

    // reads an UTF-8 string resource 
public String getStringResource(int id) throws IOException { 
    return new String(getResource(id, getContext()), Charset.forName("UTF-8")); 
} 

D'un Activité, ajoutez

public byte[] getResource(int id) throws IOException { 
     return getResource(id, this); 
} 

ou d'un cas de test , ajoutez

public byte[] getResource(int id) throws IOException { 
     return getResource(id, getContext()); 
} 

Et regarder votre gestion des erreurs - ne pas attraper et ignorer des exceptions lorsque vos ressources doivent exister ou quelque chose est (très?) Mal.

+0

Avez-vous besoin de fermer le flux ouvert par 'openRawResource()'? –

+0

Je ne sais pas, mais c'est certainement la norme. Mise à jour d'exemples – ThomasRS

1

1.Premièrement créer un dossier répertoire et nommez-première dans le dossier res 2.Créez un fichier txt dans le dossier de répertoire brut créé précédemment et lui donner tout eg.articles.txt nom .... 3.Copie et collez le texte que vous voulez dans le fichier txt vous avez créé « articles.txt » 4.dont oublier d'inclure un textview dans votre main.xml MainActivity.java

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_gettingtoknowthe_os); 

    TextView helloTxt = (TextView)findViewById(R.id.gettingtoknowos); 
    helloTxt.setText(readTxt()); 

    ActionBar actionBar = getSupportActionBar(); 
    actionBar.hide();//to exclude the ActionBar 
} 

private String readTxt() { 

    //getting the .txt file 
    InputStream inputStream = getResources().openRawResource(R.raw.articles); 

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 

    try { 
     int i = inputStream.read(); 
     while (i != -1) { 
      byteArrayOutputStream.write(i); 
      i = inputStream.read(); 
     } 
     inputStream.close(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return byteArrayOutputStream.toString(); 
} 

Je espère que ça a fonctionné!

0

Voici un mélange de solutions de week-end et de Vovodroid.

Il est plus correct que la solution de Vovodroid et plus complet que la solution de Weekens.

try { 
     InputStream inputStream = res.openRawResource(resId); 
     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); 
      try { 
       StringBuilder result = new StringBuilder(); 
       String line; 
       while ((line = reader.readLine()) != null) { 
        result.append(line); 
       } 
       return result.toString(); 
      } finally { 
       reader.close(); 
      } 
     } finally { 
      inputStream.close(); 
     } 
    } catch (IOException e) { 
     // process exception 
    } 
0
InputStream is=getResources().openRawResource(R.raw.name); 
BufferedReader reader=new BufferedReader(new InputStreamReader(is)); 
StringBuffer data=new StringBuffer(); 
String line=reader.readLine(); 
while(line!=null) 
{ 
data.append(line+"\n"); 
} 
tvDetails.seTtext(data.toString()); 
Questions connexes