[英]Android reading from file on SD Card
I am trying to read in some data from a text file I created on my SDcard. 我正在尝试从我在SD卡上创建的文本文件中读取一些数据。 However, when I am done reading it in, the stringbuilder is still blank. 但是,读完后,stringbuilder仍然为空。 I don't know if it isn't reading the file. 我不知道它是否不读取文件。 I looked on the android device monitor and the fie exists with data in it. 我在android设备监视器上看了看,fie存在其中的数据。 It is on my sdcard inside a "Notes" directory. 它在我的sdcard上的“ Notes”目录中。 Here is the code. 这是代码。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
welcomeText = (TextView) findViewById(R.id.welcomeText);
userName = (EditText) findViewById(R.id.userName);
submitButton = (Button) findViewById(R.id.submitButton);
password = (EditText) findViewById(R.id.passInput);
viewAll = (Button) findViewById(R.id.viewAll);
submitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
generateNoteOnSD("info", userName.getText().toString() + "," +password.getText().toString() );
}
});
viewAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard, "info");
String line;
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
}
welcomeText.setText("Welcome, " + text);
}
});
}
public void generateNoteOnSD(String sFileName, String sBody){
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
}
Try to change like below 尝试如下更改
viewAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "/Notes/info";
File myFile = new File(baseDir + File.separator + fileName);
try {
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String text = "";
String aDataRow = "";
while ((aDataRow = myReader.readLine()) != null) {
text += aDataRow + "\n";
}
}
catch (IOException e) {
}
welcomeText.setText("Welcome, " + text);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.