我使用以下代码从文本文件中读取值。但是,始终读取null值( versionfile 始终为null)。我在代码中遗漏了什么吗? (注意:文件已存在且值在其中)
String fileversion = Environment.getExternalStorageDirectory() + File.separator + "chk.txt", versionfile = "0";
File chkfile = new File(fileversion);
try {
BufferedReader br = new BufferedReader(new FileReader(chkfile));
while ((versionfile = br.readLine()) != null) {
}
br.close();
} catch (IOException e) {
}
答案 0 :(得分:0)
我认为你提到的文件不存在,因为当我在我的设备中执行此代码时,它完美地工作并在日志中显示输出
String fileversion = Environment.getExternalStorageDirectory() + File.separator + "Links.txt", versionfile = "0";
File chkfile = new File(fileversion);
Log.e("///////////////", "versionfile :: " + versionfile + " : fileversion :: " + fileversion);
try {
BufferedReader br = new BufferedReader(new FileReader(chkfile));
while ((versionfile = br.readLine()) != null) {
Log.e("///////////////", "versionfile ::" + versionfile + ": fileversion :: " + fileversion);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
这就是我所做的一切
您的代码非常完美,只需要将版本字符串存储在另一个像
这样的字符串中newString += versionfile;
答案 1 :(得分:0)
这样做:
String fileversion=Environment.getExternalStorageDirectory() + File.separator + "chk.txt", versionfile="0";
FileReader fileReader = new FileReader(fileversion);
try {
BufferedReader br = new BufferedReader(fileReader);
while ((versionfile = br.readLine()) != null) {
System.out.println("versionfile");
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
答案 2 :(得分:0)
使用以下代码阅读.txt文件:
// Read text from file
public void ReadBtn() {
//reading text from file
try {
FileInputStream fileIn = openFileInput("mytextfile.txt"); // define your path.
InputStreamReader InputRead = new InputStreamReader(fileIn);
char[] inputBuffer = new char[50];
String s = "";
int charRead;
while ((charRead = InputRead.read(inputBuffer)) > 0) {
// char to string conversion
String readstring = String.copyValueOf(inputBuffer, 0, charRead);
s += readstring;
}
InputRead.close();
Log.d("File Data", s);
} catch (Exception e) {
e.printStackTrace();
}
}
我希望您在清单文件中添加以下权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
答案 3 :(得分:0)
我发现了问题。
while
循环执行了2次,我的文件只有1行,所以第二次将值替换为null。根据要求,文件将始终具有单行内容。所以,我删除了while
循环,它运行正常。
String fileversion = Environment.getExternalStorageDirectory() + File.separator + "chk.txt", versionfile = "0";
File chkfile = new File(fileversion);
try {
BufferedReader br = new BufferedReader(new FileReader(chkfile));
versionfile = br.readLine();
}
br.close();
} catch (IOException e) {
}