使用InputStream读取文本文件

26

我该如何在安卓应用中读取文本文件:

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

这样我就可以获得一个类似于字符串的返回值:

"something written\nin this file\nis to be read by\nthe InputStream"

我所想的是(伪代码):

make an inputstream
is = getAssest().open("textfile.txt");  //in try and catch
for loop{
string = is.read() and if it equals "." (i.e. from 1., 2., 3. etc) add "/n" ...
}
3个回答

36

试试这个

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

14

使用 BufferedReader 读取输入流。由于 BufferedReader 从字符输入流中读取文本,缓冲字符以便提供对字符、数组和行的有效读取,所以效率较高。 InputStream 表示字节输入流。 reader.readLine() 将逐行读取文件。

BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
    out.append(line);   // add everything to StringBuilder 
    // here you can have your logic of comparison.
    if(line.toString().equals(".")) {
        // do something
    } 

}

1
File fe = new File("abc.txt");
FileInputStream fis = new FileInputStream(fe);
byte data[] = new byte[fis.available()];
fis.read(data);
fis.close();
String str = new String(data);
System.out.println(str);

为了更好地理解和使用您的代码,提供上下文会非常有帮助。 - Adonis
如果你有一个txt文件想要使用FileInputStream读取其中的文本,你可以这样做......在你的代码中加入以下内容:File fe=new File(abc.txt);,并将读取到的数据打印在控制台上,代码如下:String str=new String(data); System.out.println(str); - Ziyad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接