2010-11-03 15 views
95

Las cosas son simples pero no funcionan como se supone que deben hacerlo.Archivo de texto sin formato de lectura de Android

Tengo un archivo de texto agregado como recurso sin formato. El archivo de texto contiene texto como:

b) Si la ley aplicable requiere NINGUNA GARANTÍA CON RESPECTO A LA SOFTWARE, tales garantías estará LIMITADA A NOVENTA (90) DÍAS A PARTIR DE LA FECHA DE ENTREGA .

(c) Cualquier otra información oral o escrita consejo dado por ORIENTEERING VIRTUAL, sus distribuidores, distribuidores, agentes O EMPLEADOS constitución de una garantía OR DE CUALQUIER FORMA aumentar el alcance de CUALQUIER GARANTÍA AQUÍ .

(d) (sólo EE.UU.) Algunos estados no permiten la exclusión de IMPLÍCITAS garantías, por lo que la exclusión anterior NO APLICACIÓN. ESTA GARANTÍA OTORGA USTEDES DERECHOS LEGALES ESPECÍFICOS Y PUEDE QUE TAMBIÉN TIENE OTROS DERECHOS LEGALES QUE VARÍAN DE ESTADO A ESTADO.

en mi pantalla tengo una disposición como ésta:

<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> 

El código para leer el recurso prima es:

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

El texto obtener de mostró pero después de cada línea me sale una personaje extraño [] ¿Cómo puedo eliminar ese personaje? Creo que es New Line.

SOLUCIÓN DE TRABAJO

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

Respuesta

54

¿Qué pasa si se utiliza un BufferedReader basada en caracteres en lugar de InputStream basada en bytes?

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

No olvide que readLine() omite las líneas nuevas!

140

Puede utilizar este:

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

No estoy seguro de la Inputstream.available() es la elección correcta aquí, en lugar de leer n a un ByteArrayOutputStream hasta el n == -1. – ThomasRS

+12

Esto puede no funcionar para grandes recursos. Depende del tamaño del buffer de lectura de inputstream y solo podría devolver una parte del recurso. – d4n3

+4

@ d4n3 es correcto, la documentación del método de flujo de entrada disponible indica: "Devuelve un número estimado de bytes que se pueden leer u omitir sin bloquear para más entrada. Tenga en cuenta que este método proporciona una garantía tan débil que no es muy útil en la práctica " – ozba

2

Este es otro método que sin duda trabajar, pero no puedo conseguir a leer varios archivos de texto para ver en múltiples textviews en una sola actividad, cualquiera puede ayudar?

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 que puede hacer esto a modo similar como

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 utiliza IOUtils de "commons-io" Apache es aún más fácil:

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

Dependencias : 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

¿Qué debo importar para usar IOUtils? –

+1

Apache commons-io library (http://commons.apache.org/proper/commons-io/). O si usa Maven (http://mvnrepository.com/artifact/commons-io/commons-io). – tbraun

+6

Para gradle: compilar "commons-io: commons-io: 2.1" – JustinMorris

3

Más bien lo hacen de esta manera:

// 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")); 
} 

Desde un Actividad, añaden

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

o de un caso de prueba , añadir

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

y ver su manejo de errores - no coger y hacer caso omiso excepciones cuando deben existir los recursos o algo es (muy?) Mal.

+0

¿Necesitas cerrar el flujo abierto por 'openRawResource()'? –

+0

No lo sé, pero ciertamente es estándar. Actualizando ejemplos. – ThomasRS

1

1.En primer lugar crear una carpeta del directorio y el nombre de prima dentro de la carpeta res 2.Crear un archivo .txt dentro de la carpeta del directorio prima que creó anteriormente y darle el nombre eg.articles.txt .... 3.Copia y pegar el texto que desee dentro del archivo .txt que ha creado "articles.txt" 4.Dont se olvide de incluir un TextView en su 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(); 
} 

espero que funcionó!

0

Aquí va la mezcla de las soluciones de weekens y Vovodroid.

Es más correcto que la solución de Vovodroid y más completo que la solución 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()); 
Cuestiones relacionadas