首页 > 解决方案 > 如何从 Firebase 数据库制作 .txt 文件?

问题描述

databaseReference.child("chat").child(chatName).addValueEventListener(new ValueEventListener() 
  {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) 
    {
       for(DataSnapshot snapshot : dataSnapshot.getChildren())
       {
         Log.d("ChatActivity", "ValueEventListener : "+chatName + snapshot.getValue() + "\n");
       }
  }

当我运行 Log.d

2019-11-26 16:23:32.928 2599-2599/com.test.myapplication D/ChatActivity: ValueEventListener : TESTCHAT{time= AM 7:23, message=test1, userName=USER1}
2019-11-26 16:23:32.928 2599-2599/com.test.myapplication D/ChatActivity: ValueEventListener : TESTCHAT{time= AM 7:23, message=test2, userName=USER1}

我想制作从“Firebase 数据库聊天日志”中获取的 txt 文件,我
该怎么办?

标签: androidfirebasefirebase-realtime-database

解决方案


要创建一个 txt 文件,然后在 for 循环中执行以下操作:

try {
  File logTxt = new File("log.txt");
  FileOutputStream is = new FileOutputStream(logTxt);
  OutputStreamWriter osw = new OutputStreamWriter(is);    
  Writer w = new BufferedWriter(osw);
  w.write(snapshot.getValue(String.class));
  w.close();
} catch (IOException e) {
  System.err.println("Problem writing to the file log.txt");
}

初始化 File 的一个新实例,并为其指定要创建的 txt 文件的路径,然后使用 将数据BufferedWriter写入snapshot文件。


推荐阅读