0

i need a solution for reading a text file which was stored in internal storage. i don't want to read it line by line. without use looping how to read a complete text file and store it into a string.

BufferedReader br;
String line;
String data = "";
// String text="";
try {
    br = new BufferedReader(new FileReader(new File(Environment.getExternalStorageDirectory(), "queue_mgr.txt")));
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    br.close();
}
Walery Strauch
  • 6,792
  • 8
  • 50
  • 57
Kalai Prakash
  • 141
  • 1
  • 8
  • 1
    Possible duplicate of [read complete file without using loop in java](http://stackoverflow.com/questions/14169661/read-complete-file-without-using-loop-in-java) – Yury Fedorov Oct 26 '16 at 13:31
  • I think that solution won't work in Android. – ig343 Oct 26 '16 at 13:36
  • What do you want to achieve? There will be looping at some level. Even if there were an API to copy a text file, the implementation of that API would have looping of some sort. If you want something more efficient, you might be able to using a large byte buffer instead of text. See my answer below. – Peri Hartman Oct 26 '16 at 13:39
  • i need to send json object to server. – Kalai Prakash Oct 26 '16 at 13:41
  • it will read internal storage and converted into json object.i need to know how to read complete filw without read line by line – Kalai Prakash Oct 26 '16 at 13:42
  • 1
    Any reading file will be read line by line, maybe you will not see it at a high level, but the class will do just that. However why would you not read it line by line? – Paolo Mastrangelo Oct 26 '16 at 13:49
  • Because am using for loop for json object the text file will be convert as a json object. – Kalai Prakash Oct 26 '16 at 18:28

1 Answers1

0

You can use a large byte buffer and gain some efficiency:

try
{
  InputStream in = new FileInputStream (from);
  OutputStream out = new FileOutputStream (to);

  // Transfer bytes from in to out
  byte[] buf = new byte[1024 * 10]; // 5MB would be about 500 iterations
  int len;
  while ((len = in.read (buf)) > 0)
    out.write (buf, 0, len);

  in.close ();
  out.close ();
  }
}
catch (FileNotFoundException e)
{
  ...
}
catch (IOException e)
{
  ...
}
Peri Hartman
  • 19,314
  • 18
  • 55
  • 101