Java 文件输入流/加载简单的txt文件

Java 文件输入流/加载简单的txt文件,java,android,Java,Android,有人知道为什么会崩溃吗?我所做的就是从我的原始文件夹中读取txt文件中的一个文件,当我单击“其他活动”窗口中的“加载”按钮时,当我在文件读取器对象中调用变量测试时,代码中断。log.d(null,ReadFileObject.fileText)提前感谢 public class ReadFile extends Activity{ public String test; public String testing; protected void onCreate(Bundle savedInst

有人知道为什么会崩溃吗?我所做的就是从我的原始文件夹中读取txt文件中的一个文件,当我单击“其他活动”窗口中的“加载”按钮时,当我在文件读取器对象中调用变量测试时,代码中断。log.d(null,ReadFileObject.fileText)提前感谢

public class ReadFile extends Activity{
public String test;
public String testing;
protected void onCreate(Bundle savedInstanceState) {
}
 public void fileText() {
    InputStream fis;
    fis =  getResources().openRawResource(R.raw.checkit);
    byte[] input;
    try {
        input = new byte [fis.available()];
        while(fis.read() != -1)
        {
            test += new String (input);
        }
        testing = test;
        fis.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println(e.getMessage());
    }catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    System.out.println(e.getMessage());
}

/* InputStream fis = null;
try {
    fis = getResources().openRawResource(R.raw.checkit);
    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
    String nextLine;
    int i = 0, j = 0;
    while ((nextLine = br.readLine()) != null) {
        if (j == 5) {
            j = 0;
            i++;
        }
       test += nextLine;
    }
} catch (Exception e) {
    e.printStackTrace();
    System.out.println(e.getMessage());
} finally {
    if (fis != null) {
        try { fis.close(); }
        catch (IOException ignored) {}
    }
}*/

}
}

您的类扩展了
`activity
,但在创建时
中没有任何内容。如果您需要一个简单的
java
程序,请尝试创建
新的java项目
。既然您扩展了
活动
,您就应该
设置内容视图(您的布局)
。然后从oncreate调用您的
方法
,然后执行您的操作

您的代码在此处被破坏:

byte[] input;
input = new byte [fis.available()];
while(fis.read() != -1) {
    test += new String (input);
}
testing = test;
fis.close();
在Java中,
available()
不可靠。。。。甚至可能返回0。您应该改为使用类似以下内容的循环:

InputStream fis = getResources().openRawResource(R.raw.checkit);
try {
    byte[] buffer = new byte[4096]; // 4K buffer
    int len = 0;
    while((len = fis.read(buffer)) != -1) {
        test += new String (buffer, 0, len);
    }
    testing = test;
} catch (IOException ioe) {
    ioe.printStackTrace();
    // make sure you do any other appropriate handling.
} finally {
    fis.close();
}

(虽然使用字符串连接可能不是最好的主意,但使用StringBuilder)。

这是缩进,android看了一眼就跑开了……)哈哈,非常有趣。你们有什么建议吗?如果你不知道的话,我是新来安卓的。只是做了一些编码,它看起来好像在输入流和字节输入之间中断。是的,我在解决崩溃问题,而不是100%的正确性,虽然我会编辑。好的,酷,我正在取得进展。它现在说它正在撞击fis物体。我生成了一个新的文本文件,并将其重命名,但它仍在崩溃。。我只是通过点击按钮来调用这个类,实际上不需要布局。。但至少如此。因此,请从中删除extend活动和oncreate。将其用作普通类,因为代码越复杂,调试就越困难