從文件和打印文本,我認爲我的代碼正在讀取文件的權利,但是當我運行應用程序,輸出的「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
同意@Buddy沒有辦法該文件存在於設備上。另一個問題是你正在以一個while循環正在讀取文件的速度更新文本字段。你永遠不會看到文字更新。更可能的是,當您正確地閱讀文件時,您只會看到文件的最後一行。 –
雖然我在模擬器上運行它。 – pro