Leer archivo de texto sin procesar de Android

Tengo un archivo words.txt que he colocado en mi carpeta res / raw . Las palabras del archivo están separadas por espacio. Me cuesta mucho escribir el código de Android / Java para leer el archivo palabra por palabra.

Lo más sencillo es utilizar un escáner .

 Scanner s = new Scanner(getResources().openRawResource(R.raw.text_file)); try { while (s.hasNext()) { String word = s.next(); // .... } } finally { s.close(); } 

El delimitador predeterminado es el espacio en blanco (incluido el espacio). Si desea que sólo se dispare en el uso de espacio s.useDelimiter(" "); Después de crearlo.

 //put your text file to raw folder, raw folder must be in resource folder. private TextView tv; private Button btn; btn = (Button)findViewById(R.id.btn_json); tv = (TextView)findViewById(R.id.tv_text); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { SimpleText(); } }); private void SimpleText(){ try { InputStream is = this.getResources().openRawResource(R.raw.simpletext); byte[] buffer = new byte[is.available()]; while (is.read(buffer) != -1); String jsontext = new String(buffer); tv.setText(jsontext); } catch (Exception e) { Log.e(TAG, ""+e.toString()); } } 

Para obtener las palabras del archivo de carpeta sin procesar, intente con el siguiente método

Leer los datos de la carpeta raw usando getResources().openRawResource(R.raw.song);
A continuación, obtener los datos inputtream en una matriz de bytes dividir los datos con el espacio.

Utilice el código siguiente

 InputStream is =getResources().openRawResource(R.raw.song); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } byte[] myData = baf.toByteArray(); String dataInString = new String(myData); String[] words = dataInString.split(" "); 

Gracias Deepak

Tuve esta misma pregunta y mientras que las respuestas anteriores son probablemente correctas no pude conseguir que funcionen correctamente. Esto fue casi seguro error de operador y la ignorancia de mi parte – pero sólo en caso de que alguien quiere ver cómo yo – un n00b – finalmente lo hizo, aquí está mi solución:

 // this is just the click handler for a button... public void loadStatesHandler(View v) { try { String states = getStringFromRaw(this); readOutput.setText(states); } catch(Throwable t) { t.printStackTrace(); } } private String getStringFromRaw(Context c) throws IOException { Resources r = c.getResources(); InputStream is = r.openRawResource(R.raw.states); String statesText = convertStreamToString(is); is.close(); return statesText; } private String convertStreamToString(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int i = is.read(); while (i != -1) { baos.write(i); i = is.read(); } return baos.toString(); } 

No estoy exactamente seguro de por qué esto funcionó para mí cuando lo anterior no, ya que no parece fundamentalmente diferente – pero como he dicho – fue probablemente error de mi parte.

Lectura de res/raw carpeta res/raw a String

 InputStream inputStream = getResources().openRawResource(R.raw.yourtextfile); BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(inputStream)); String eachline = bufferedReader.readLine(); while (eachline != null) { // `the words in the file are separated by space`, so to get each words String[] words = eachline.split(" "); eachline = bufferedReader.readLine(); } 
  • ¿Cómo leer un archivo en un mapa de bits de Java?
  • ¿Cómo puede acceder la aplicación a los archivos de almacenamiento USB OTG en Android 6.0 (API nivel 23) sin root?
  • Selector de archivos de Android
  • ¿Cómo agregar un archivo a un proyecto de Android, desplegarlo en el dispositivo y abrirlo?
  • Leer archivo local en Phonegap
  • File.list () devuelve null para directorio
  • Leer EPUB utilizando sólo Java
  • Permiso denegado al crear nuevo archivo en almacenamiento externo
  • ¿Cómo pasar una ruta de acceso de archivo que está en la carpeta assets a File (String path)?
  • Android: Cómo hacer que los archivos de los elementos del juego sean legibles desde el código c ++ usando ndk
  • Cómo crear un archivo en un directorio SDCARD
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.