我用这code。
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("config.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((br.readLine()) != null) {
temp1 = br.readLine();
temp2 = br.readLine();
}
in.close();
}catch (Exception e){//Catch exception if any
Toast.makeText(getBaseContext(), "Exception", Toast.LENGTH_LONG).show();
}
Toast.makeText(getBaseContext(), temp1+temp2, Toast.LENGTH_LONG).show();
不过这正显示出异常,并没有更新和的temp1 TEMP2。
but this is showing exception and is not updating temp1 and temp2.
您看到的例外 - 我会强烈推荐)捕捉尽可能特定类型,例如 IOException异常
,和b)登录或消息或堆栈跟踪显示,和c)至少在LogCat中,如果你是编程检查,从DDMS透视图日食 - 很可能是由于到Android没有找到的config.txt
文件,您试图打开。通常情况下,对于简单的情况下,如你的,是私人使用 openFileInput
打开应用程序文件 - 详见文档。
The exception you see - that I would strongly recommend a) to catch as a specific type, e.g. IOException
, and b) to log or show with a message or a stack trace, and c) at least to check for in LogCat, from the DDMS perspective if you are programming with Eclipse - is probably due to Android not finding the config.txt
file you are trying to open. Usually, for the simplest cases such as yours, files that are private to an application are opened using openFileInput
- see the documentation for details.
除了例外,你的阅读循环是有缺陷的:你需要在进入之前初始化一个空字符串,并在,而
状态填充
Apart from the exception, your reading loop is defective: you need to initialize an empty string before entering, and fill it in the while
condition.
String line = "";
while ((line = br.readLine()) != null) {
// do something with the line you just read, e.g.
temp1 = line;
temp2 = line;
}
不过,你不需要一个循环,如果你只是想保存不同的变量的前两行。
However, you don't need a loop if you just want to save the first two lines in different variables.
String line = "";
if ((line = br.readLine()) != null)
temp1 = line;
if ((line = br.readLine()) != null)
temp2 = line;
正如其他人已经指出,调用的readLine
消耗行,所以如果你的的config.txt
文件包含只有一行的code消耗它放在,而
条件,那么 temp1目录
和 TEMP2
GET 空
分配,因为没有阅读更多的文字。
As others have already pointed out, calling readLine
consumes a line, so if your config.txt
file contains only one line your code consumes it on the while
condition, then temp1
and temp2
get null
assigned because there's no more text to read.
上一篇:与排球异步帐户认证排球、帐户
下一篇:蓝牙低能量的扫描失败蓝牙、能量