如何从.txt文件中读取 [英] How to read from .txt file

查看:194
本文介绍了如何从.txt文件中读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从文件中读取是在服务器上present文本,包含文本文件的Hello World,现在我想要写的TextView这个文本。我有进口所有需要的软件包。在此先感谢

 公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);        TextView的电视=新的TextView(本);        尝试{
            网址器updateURL =新的URL(HTTP://--------------------/foldername/hello.txt);
            康涅狄格州的URLConnection = updateURL.openConnection();
            InputStream为= conn.getInputStream();
            二BufferedInputStream为=新的BufferedInputStream(是);
            ByteArrayBuffer BAF =新ByteArrayBuffer(50);            INT电流= 0;
            而((电流= bis.read())!= - 1){
                 baf.append((字节)电流);
            }
            最后一个String =新的String(baf.toByteArray());
            ((的TextView)TV).setText(S);        }赶上(例外五){
        }
    };


解决方案

试试这个功能....

 公共静态字符串convertStreamToString(InputStream为)抛出异常{
        读者的BufferedReader =新的BufferedReader(新的InputStreamReader(是));
        StringBuilder的SB =新的StringBuilder();
        串线= NULL;        而((行= reader.readLine())!= NULL){
            sb.append(线);
        }        is.close();        返回sb.toString();
    }

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) {
        }
    };

解决方案

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();
    }

这篇关于如何从.txt文件中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆