La Chi
La Chi

Reputation: 585

How to read from .txt file

i am trying to read the text from a file which is present on server, this file containing the text "hello world" ,now i want to write this text on TextView . i have imported all required packages . thanks in advance

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TextView tv = new TextView(this);

        try {
            URL updateURL = new URL("http://--------------------/foldername/hello.txt");                
            URLConnection conn = updateURL.openConnection(); 
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(50);

            int current = 0;
            while((current = bis.read()) != -1){
                 baf.append((byte)current);
            }


            final String s = new String(baf.toByteArray());     
            ((TextView)tv).setText(s); 





        } catch (Exception e) {
        }
    };

Upvotes: 0

Views: 576

Answers (2)

kalandar
kalandar

Reputation: 823

try this code

 URL url = new URL(urlpath);
 BufferedInputStream bis = new BufferedInputStream((url.openStream()));
 DataInputStream dis = new DataInputStream(bis);
 String full = "";
 String line;
 while ((line=dis.readLine())!=null) {
     full +=line;               
  }      
bis.close();
dis.close();

((TextView)tv).setText(full); 

Upvotes: 0

Dheeresh Singh
Dheeresh Singh

Reputation: 15701

try this function ....

 public static String convertStreamToString(InputStream is) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }

        is.close();

        return sb.toString();
    }

Upvotes: 1

Related Questions