在内部存储中保存csv日志文件



描述:我正试图将来自firestore的数据记录到csv文件中,我有以下方法来完成。

public interface ExportPojo {
String generateExportValues();
String generateExportHeaders();}

public static File generateCSV(Context context, Collection<? extends ExportPojo> values, Class<? extends ExportPojo> type) {
StringBuilder csv = new StringBuilder();
String header;
try {
header = type.newInstance().generateExportHeaders();
} catch (Exception e) {
e.printStackTrace();
return null;
}
csv.append(header).append("n");
for (ExportPojo entry : values) {
csv.append(entry.generateExportValues());
csv.append("n");
}
return writeStringToFile(context, csv.toString(), ".csv");
}

public static File writeStringToFile(Context context, String data, String format) {
File dir = new File(context.getFilesDir(), "/manage/");
// create this directory if not already created
dir.mkdir();
// create the file in which we will write the contents
String timestamp =
new SimpleDateFormat("E MMM yyyy H-m-s", Locale.getDefault()).format(new Date());
final File file = new File(dir, timestamp + format);
try {
FileOutputStream os = new FileOutputStream(file);
os.write(data.getBytes());
os.close();
return file;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

问题:客户端希望用户浏览文件目录,找到csv文件并打开它。但在运行这些方法后,我找不到导出的文件。我已经记录了csv.tostring(),看起来数据还可以。我做错了什么?

context.getFilesDir()为您提供文件目录的路径,该目录位于Android的/data中的应用程序文件夹中,普通用户无法访问该文件夹。为了让用户可以访问该文件,您需要将其保存在公共目录中。

你可以这样做:(代码在kotlin中,但你可以很容易地用JAVA转换(

val path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
val dir = File(path.absolutePath)
if(!dir.exists())
dir.mkdirs()
val file = File("$path/Text.txt")
if (!file.exists()) {
file.createNewFile();
}
var content = ""    //todo: write your csv content here
val fw = FileWriter(file.absoluteFile)
val bw = BufferedWriter(fw)
bw.write(content)
bw.close()
file.renameTo(File("$path/${name}.csv"))
File("$path/Text.txt").delete()

你也可以尝试直接将内容写入.csv而不是.txt,但对我来说失败了。

最新更新