studio programacion para móviles libro edición desarrollo desarrollar curso aprende aplicaciones android text resources

para - manual de programacion android pdf



Archivo de recursos sin formato de lectura de texto de Android (9)

¿Qué sucede si utiliza un BufferedReader basado en caracteres en lugar de un 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!

Las cosas son simples pero no funcionan como se supone.

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

b) SI LA LEY APLICABLE REQUIERE ALGUNA GARANTÍA CON RESPECTO AL SOFTWARE, TODAS DICHAS GARANTÍAS ESTÁN LIMITADAS EN DURACIÓN A NOVENTA (90) DÍAS DESDE LA FECHA DE ENTREGA.

(c) NINGUNA INFORMACIÓN ORAL O ESCRITA O LOS CONSEJOS OTORGADOS POR ORIENTACIÓN VIRTUAL, SUS DISTRIBUIDORES, AGENTES O EMPLEADOS CREARÁN UNA GARANTÍA O DE CUALQUIER FORMA INCREMENTARÁ EL ALCANCE DE CUALQUIER GARANTÍA PROPORCIONADA AQUÍ.

(d) (solo EE. UU.) ALGUNOS ESTADOS NO PERMITEN LA EXCLUSIÓN DE GARANTÍAS IMPLÍCITAS, POR LO QUE LA EXCLUSIÓN ANTERIOR PODRÍA NO APLICARSE EN SU CASO. ESTA GARANTÍA LE OTORGA DERECHOS LEGALES ESPECÍFICOS Y TAMBIÉN PUEDE TENER OTROS DERECHOS LEGALES QUE VARÍAN DE UN ESTADO A OTRO.

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 en 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 aparece, pero después de cada línea aparece un 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(); }


1.Primero crea una carpeta de Directorio y nómbrala dentro de la carpeta res 2. crea un archivo .txt dentro de la carpeta de directorio sin formato que creaste antes y dale cualquier nombre eg.articles.txt .... 3.copia y pega el texto que desea dentro del archivo .txt que creó "articles.txt" 4.dont olvide incluir una vista de texto en 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ó!


@borislemke puedes hacer esto de manera similar a 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(); }


Aquí va una 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 }


Este es otro método que definitivamente funcionará, pero no puedo leer múltiples archivos de texto para verlos en múltiples vistas de texto en una sola actividad. ¿Alguien puede ayudarme?

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


Más bien hazlo 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 observe su manejo de errores: no atrape e ignore las excepciones cuando sus recursos deben existir o algo está (¿muy?) Equivocado.


Puedes usar 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 usa 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''


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