gpt4 book ai didi

java - Android从SD卡上读取文件

转载 作者:太空宇宙 更新时间:2023-11-04 13:32:54 25 4
gpt4 key购买 nike

我正在尝试从我在 SD 卡上创建的文本文件中读取一些数据。然而,当我读完它时,字符串构建器仍然是空白的。不知道是不是没读到文件。我查看了 Android 设备监视器,文件中存在数据。它位于我的 SD 卡上的“Notes”目录中。这是代码。

   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();
}
}

最佳答案

尝试如下更改

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);

}
});

关于java - Android从SD卡上读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31991285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com