Reading a textfile using InputStream

前端 未结 3 1157
耶瑟儿~
耶瑟儿~ 2020-12-31 01:04

How can I read a text file like in android app:

\"1.something written
2.in this file
3.is to be read by
4.the InputStream
...\"

so I can be

3条回答
  •  自闭症患者
    2020-12-31 01:13

    try this

    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.Toast;
    import java.io.*;
    
    public class FileDemo1 extends Activity {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            try {
                playWithRawFiles();
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(), "Problems: " + e.getMessage(), 1).show();
            }
        }
    
        public void playWithRawFiles() throws IOException {      
            String str = "";
            StringBuffer buf = new StringBuffer();            
            InputStream is = this.getResources().openRawResource(R.drawable.my_base_data);
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                if (is != null) {                            
                    while ((str = reader.readLine()) != null) {    
                        buf.append(str + "\n" );
                    }                
                }
            } finally {
                try { is.close(); } catch (Throwable ignore) {}
            }
            Toast.makeText(getBaseContext(), buf.toString(), Toast.LENGTH_LONG).show();
        }
    }
    

提交回复
热议问题