【发布时间】:2018-08-22 22:18:53
【问题描述】:
这是写入文件的代码。这里使用的 SecurityUtils 类是将字符串编码为 AES/CBC。
public static boolean reWriteToFile(String str1,
String str2, String str3, String str4) {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
SecurityUtils securityUtils = new SecurityUtils();
String st = securityUtils.getEncryptedToken(str1) + "\n" + securityUtils.getEncryptedToken(str2) + "\n" + securityUtils.getEncryptedToken(str3) + "\n" + securityUtils.getEncryptedToken(str4);
Logger.i("STRING_TO_WRITE", st);
File externalStorageDir = Environment.getExternalStorageDirectory();
File myFile = new File(externalStorageDir, APP_CONFIG_FILE_NAME);
try {
FileOutputStream fOut1 = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut1);
myOutWriter.append(st);
myOutWriter.close();
fOut1.close();
} catch (Exception e) {
e.printStackTrace();
}
return true;
} else {
return false;
}
}
这是从文件中读取的代码:
public static boolean readFromFile() {
SecurityUtils securityUtils = new SecurityUtils();
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File externalStorageDir = Environment.getExternalStorageDirectory();
File myFile = new File(externalStorageDir, APP_CONFIG_FILE_NAME);
if (myFile.exists()) {
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(myFile)));
String data;
StringBuffer sb = new StringBuffer();
while ((data = br.readLine()) != null) {
sb.append(data + ",");
}
String str = sb.toString().replace(",,", ",");
String[] both = str.split(",");
Log.d("3rd string", both[3]);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
return false;
} else
return false;
}
但在 both[3] 的日志中,我只得到第 5 行,如图所示,我需要第 5 到第 9 行,而 第一行是没有换行符的字符串 第三个也是一个没有换行符的字符串 5th-9th 也是一个没有换行符的字符串 11th 也是一个没有换行符的字符串。 但是每个不同的字符串之间都有一个换行符
这些都是 AES/CBC 编码的字符串 不是全部。
【问题讨论】:
-
如果您正在向文件写入一个带有 3 个换行符的字符串,为什么要获得 11 行文本?
-
这4个字符串是存储在同一个文件中的不同数据,用换行符分隔
-
叫我这么愚蠢,但我不明白你的问题。我已经测试了你的代码,它工作正常。我刚刚将您的四个动态字符串替换为静态字符串,所有我使用第一种方法写入文件的内容,我使用第二种方法读取。你只记录第四个字符串,让循环它,你会看到整个输出。或者只记录 StringBuffer 以将您的输出显示为单个字符串。
-
如果所有字符串的长度都较短,则不会有问题。如果字符串像第三个那样长,问题仍然存在
标签: android file android-file