从android中的文本文件中读取

时间:2012-03-26 10:07:53

标签: java android file

我试图从文件中读取随机行。我的代码没有错误,只要在模拟器中运行就会关闭一个强制关闭,我无法解决原因!

public class filereader extends Activity {
     TextView t = (TextView)findViewById(R.id.text);
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

Scanner s = new Scanner(getResources().openRawResource(R.raw.lev1)); {

    try { 
        while (s.hasNext()) { 
            String word = s.next(); 
            t.setText(word); 
        } 
    } 
    finally { 
        s.close(); 
    } 
}

}

3 个答案:

答案 0 :(得分:2)

  

TextView t =(TextView)findViewById(R.id.text);

在调用setContentView之前,您无法运行findViewById:

   TextView t = null;    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    t = (TextView)findViewById(R.id.text);
}

请务必在text

中声明main.xml

答案 1 :(得分:2)

这样做

    BufferedReader myReader = null;
    try 
    {
        fIn = openFileInput("customer_number.txt");         
        myReader = new BufferedReader(new InputStreamReader(fIn));
    }
    catch (FileNotFoundException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String aDataRow = "";
    //String aBuffer = "";  
    try 
    {
        while ((aDataRow = myReader.readLine()) != null) {
            aBuffer += aDataRow + "\n";
            // TO display Whole Data of File
            Toast.makeText(getBaseContext(),aBuffer,Toast.LENGTH_SHORT).show();

     }
        // To display Last Entered Number
        Toast.makeText(getBaseContext(),last_number,Toast.LENGTH_SHORT).show();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   

答案 2 :(得分:0)

public void readfromfile(){
    try {
         FileInputStream fileIn=openFileInput("mytextfile.txt");
         InputStreamReader InputRead= new InputStreamReader(fileIn);
         char[] inputBuffer= new char[READ_BLOCK_SIZE];
         int charRead;

         while ((charRead=InputRead.read(inputBuffer))>0) {
             // char to string conversion
             String readstring=String.copyValueOf(inputBuffer,0,charRead);
             String s +=readstring;
         }
         InputRead.close();
         Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();

     } catch (Exception e) {
         e.printStackTrace();
     }
}

它将按字符串读取名为“mytext.txt”的文本文件,并通过将其附加到字符串变量s来存储它。因此变量“s”包含从文件中获取的最终字符串。