I am relatively new to Java and I am trying to write a simple Android application. I have a large text file with 3500 lines in the folder with the resources of my applications, and I need to read it in a line. I found a good example on how to do this, but I have a question why the byte array is initialized to 1024. Do I want to initialize it to the length of my text file? Also, do I want to use char , not byte ? Here is the code:
private void populateArray(){ AssetManager assetManager = getAssets(); InputStream inputStream = null; try { inputStream = assetManager.open("3500LineTextFile.txt"); } catch (IOException e) { Log.e("IOException populateArray", e.getMessage()); } String s = readTextFile(inputStream); // Add more code here to populate array from string } private String readTextFile(InputStream inputStream) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); inputStream.length byte buf[] = new byte[1024]; int len; try { while ((len = inputStream.read(buf)) != -1) { outputStream.write(buf, 0, len); } outputStream.close(); inputStream.close(); } catch (IOException e) { Log.e("IOException readTextFile", e.getMessage()); } return outputStream.toString(); }
EDIT: Based on your suggestions, I tried this approach. It is better? Thanks.
private void populateArray(){ AssetManager assetManager = getAssets(); InputStream inputStream = null; Reader iStreamReader = null; try { inputStream = assetManager.open("List.txt"); iStreamReader = new InputStreamReader(inputStream, "UTF-8"); } catch (IOException e) { Log.e("IOException populateArray", e.getMessage()); } String String = readTextFile(iStreamReader); // more code here } private String readTextFile(InputStreamReader inputStreamReader) { StringBuilder sb = new StringBuilder(); char buf[] = new char[2048]; int read; try { do { read = inputStreamReader.read(buf, 0, buf.length); if (read>0) { sb.append(buf, 0, read); } } while (read>=0); } catch (IOException e) { Log.e("IOException readTextFile", e.getMessage()); } return sb.toString(); }
source share