java - why initialize this byte array to 1024 -
i'm relatively new java , i'm attempting write simple android app. have large text file 3500 lines in assets folder of applications , need read string. found example how have question why byte array initialized 1024. wouldn't want initialize length of text file? also, wouldn't want use char
, not byte
? here 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 populate array 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 suggestions, tried approach. 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 { { 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(); }
this example not @ all. it's full of bad practices (hiding exceptions, not closing streams in blocks, not specify explicit encoding, etc.). uses 1024 bytes long buffer because doesn't have way of knowing length of input stream.
read java io tutorial learn how read text file.
Comments
Post a Comment