如何在android中逐行阅读?
我正在使用此代码。
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();
但是这显示exception并且没有更新temp1和temp2。
您看到的exception – 我强烈建议a)捕获特定类型,例如IOException
,以及b)记录或显示消息或堆栈跟踪,以及c)至少在LogCat中检查,从如果您使用Eclipse编程,DDMS透视图可能是因为Android没有找到您尝试打开的config.txt
文件。 通常,对于像您这样的最简单的情况,使用openFileInput
打开应用程序专用的文件 -有关详细信息, 请参阅文档 。
除了exception之外,您的读取循环有缺陷:您需要在进入之前初始化空字符串,并在while
条件下填充它。
String line = ""; while ((line = br.readLine()) != null) { // do something with the line you just read, eg temp1 = line; temp2 = line; }
但是,如果您只想将前两行保存在不同的变量中,则不需要循环。
String line = ""; if ((line = br.readLine()) != null) temp1 = line; if ((line = br.readLine()) != null) temp2 = line;
正如其他人已经指出的那样,调用readLine
会消耗一行,所以如果你的config.txt
文件只包含一行你的代码在while
条件下使用它,那么temp1
和temp2
会被赋值为null
因为没有更多的文本可供读取。
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)); String line = ""; while ((line = br.readLine()) != null) { temp1 = line; temp2 = line; } 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();
br.readLine()虽然已经消耗了一条线。
试试这个
LineNumberReader reader = new LineNumberReader(new FileReader("config.txt"))); String line; while ((line = reader.readLine()) != null) { //doProcessLine }
如果你想保存你必须要做的前两行:
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)); String line = ""; if((line = br.readLine()) != null) temp1 = line; if((line = br.readLine()) != null) temp2 = line; } catch(Exception e) { e.printStackTrace(); }
- ANDROID和PHP – 如何使用PHP从MySql显示JSONArray
- 将数组从JNI传递到Java
- 通过Programetically从App启动Skype
- 从未调用过BaseAdapter OnItemClickListener
- E / ddms IllegalArgumentException安装了32位和64位Java JRE的“错误版本”
- 在使用HtlmCleaner的Android上,非英语字符解码不正确
- 如何在android中以编程方式启用/禁用gps和移动数据?
- 如何为多人Android应用程序设置Java服务器和数据库
- Android- java.lang.IllegalArgumentException