【发布时间】:2015-10-28 17:14:44
【问题描述】:
我认为我的代码正在正确读取文件,但是当我运行应用程序时,输出是“Hello World”。这告诉我文本字段没有被覆盖。我认为问题在于while循环。这是我的java代码:
package com.example.fileio.app1_fileio;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Scanner;
import java.io.FileReader;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BufferedReader br = null;
try {
String sCurrentLine;
//get a reference to the textview in the view, this is done by referring to the textview's id: outputText
TextView t = (TextView) findViewById(R.id.textField);
String var1;
String var2;
br = new BufferedReader(new FileReader("C:\\Users\\android.txt"));
while ((sCurrentLine = br.readLine()) != null) {
var1 = sCurrentLine;
var2 = sCurrentLine;
//overwrite the text in the textview
t.setText(var1);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
//create a new file using the utility class: "FileUtility"
FileUtility myFile = new FileUtility();
Log.i("Info", "Android File Example Main Activity Completed");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
<TextView android:text="@string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textField" />
【问题讨论】:
-
您应该尝试调试它...虽然我很确定您的 Android 设备没有 C:\ 驱动器...
-
同意@Buddy 设备上不可能存在该文件。另一个问题是您正在以 while 循环读取文件的速度更新文本字段。您将永远不会看到文本更新。很可能,当您正确读取文件时,您只会看到文件的最后一行。
-
我在模拟器上运行它。
-
正如 Buddy 所说,Android 中没有 C:\ 驱动器(因为它是一个 linux 操作系统)。我猜你正在使用 Android 模拟器,它有他自己的环境。将您的文本文件放在您的 android 项目的 assets 文件夹中,然后从那里读取文件。
标签: java android bufferedreader