Archivo de recursos de texto de lectura de Android
Las cosas son simples, pero no funcionan como se supone.
Tengo un archivo de texto agregado como recurso crudo. El archivo de texto contiene texto como:
- Necesidad de formatear moneda para TextView
- Android - ¿Es posible superponer texto en texto?
- Java de Java no funciona
- ¿Cómo podemos aumentar el tamaño de la fuente en tostadas?
- Obtener texto de la página web a la cadena
B) SI LA LEY APLICABLE REQUIERE CUALQUIER GARANTÍA CON RESPECTO AL SOFTWARE, TODAS LAS GARANTÍAS ESTÁN LIMITADAS EN DURACIÓN A NOVENTA (90) DÍAS DESDE LA FECHA DE LA ENTREGA.
(C) NO HAY INFORMACIÓN O CONSEJO ORAL O ESCRITO DADO POR ORIENTACIÓN VIRTUAL, SUS DISTRIBUIDORES, DISTRIBUIDORES, AGENTES O EMPLEADOS, CREARÁ UNA GARANTÍA O, EN CUALQUIER FORMA, AUMENTARÁ EL ALCANCE DE CUALQUIER GARANTÍA PROPORCIONADA EN ESTE DOCUMENTO.
(D) (sólo para EE. UU.) ALGUNOS ESTADOS NO PERMITEN LA EXCLUSIÓN DE GARANTÍAS IMPLÍCITAS, POR LO QUE ES POSIBLE QUE LA EXCLUSIÓN ANTERIOR NO SE APLIQUE A USTED. ESTA GARANTÍA LE DA DERECHOS LEGALES ESPECÍFICOS Y USTED TAMBIÉN PUEDE TENER OTROS DERECHOS LEGALES QUE VARÍAN DE ESTADO A ESTADO.
En mi pantalla tengo un diseño como este:
<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 bruto 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 se muestra, pero después de cada línea me sale un personaje extraño [] ¿Cómo puedo eliminar ese carácter? 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(); }
- Inconsistencia al establecer el tamaño de fuente de TextView en el código y en los recursos
- ¿Cómo subraya un texto en android xml?
- ¿Cómo usar el sombreado de píxeles para lograr un texto suave?
- Cómo configurar el idioma holandés en texto a voz?
- Cómo leer un archivo de texto seleccionado de sdcard en android
- Android: cómo determinar la última letra totalmente visible en TextView?
- ¿Cómo ajustar el texto en el botón?
- Android Cambiar elementos de menú del cajón de navegación Texto por programación
¿Qué pasa si utiliza un BufferedReader basado en caracteres en lugar de InputStream basado en bytes?
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = reader.readLine(); while (line != null) { ... }
No olvide que readLine () omite las nuevas líneas!
Puede utilizar esto:
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."); }
Si utiliza IOUtils de apache "commons-io" 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'
Más bien hacerlo 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")); }
De una actividad , agregue
public byte[] getResource(int id) throws IOException { return getResource(id, this); }
O de un caso de prueba , agregue
public byte[] getResource(int id) throws IOException { return getResource(id, getContext()); }
Y ver su manejo de errores – no atrapar e ignorar las excepciones cuando sus recursos deben existir o algo es (muy?) Mal.
Este es otro método que sin duda funcionará, pero no puedo obtener para leer múltiples archivos de texto para ver en múltiples vistas de texto en una sola actividad, cualquier persona 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(); }
@borislemke puedes hacerlo de manera 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(); }
1.Primero crea una carpeta de directorio y el nombre de ella en bruto dentro de la carpeta res 2.create un archivo .txt dentro de la carpeta de directorio raw que creó anteriormente y darle cualquier nombre, por ejemplo ,.articles.txt …. 3.copy y pegar el Texto que desea dentro del archivo .txt que ha creado "articles.txt" 4.nunca 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 haya funcionado!
Aquí va mezcla de soluciones de semana 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 }
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());
- Cómo reducir el código – 65k método límite en dex
- Cómo eliminar un SMS de la bandeja de entrada en Android mediante programación?