java - android中如何读取临时数据

标签 java android temporary-files

我试图在一个 Activity 中创建一个临时文件并在另一个 Activity 中读取,因为我无法使用 Intent Bundle 发送它,为此,我试图创建这个文件。问题是,我被卡住了关于这个问题。

我已经知道如何创建临时文件:

try{

        //create a temp file
        File temp = File.createTempFile("tempfile", ".tmp");

    //write it
        BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
        bw.write("This is the temporary file content");
        bw.close();

        System.out.println("Done");

    }catch(IOException e){

        e.printStackTrace();

    }

如何获取 TempFilePath :

try{

        //create a temp file
        File temp = File.createTempFile("temp-file-name", ".tmp");

        System.out.println("Temp file : " + temp.getAbsolutePath());

    //Get tempropary file path
        String absolutePath = temp.getAbsolutePath();
        String tempFilePath = absolutePath.
            substring(0,absolutePath.lastIndexOf(File.separator));

        System.out.println("Temp file path : " + tempFilePath);

    }catch(IOException e){

        e.printStackTrace();

    }

现在我想阅读内容,我正在关注 this教程,但它对我不起作用,也许是因为我试图在类里面阅读谁不扩展 Activity?

最佳答案

如果您使用 createTempFile() 创建了临时文件,下面是如何将其读回内存的示例。

// "temp" is what you get from createTempFile().
String path = temp.getPath();

FileReader fileReader = new FileReader(path);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String buffer;
StringBuilder stringBuilder = new StringBuilder();

while ((buffer = bufferedReader.readLine()) != null) {
    stringBuilder.append(buffer);
}

// Use "stringBuilder.toString()" if you want to convert it to String.

请注意,只有当您创建的临时文件是文本文件时,这才有效;如果没有,您可能需要考虑其他方法,例如 DataInputStream。

关于java - android中如何读取临时数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42014398/

相关文章:

java - 如何使 `Map::get` 返回找到的值的 `Optional` 或 `Optional.empty()`

java - 由于 XMI 无法正确加载容器,正在加载序列化的 Ecore 模型

java - 您如何断言在 JUnit 测试中引发了某个异常?

android - 房间 : Receiving error when using @Transaction

java - 安卓 : Error SimpleDateFormat Unknown pattern character 'u'

python - PyTest:自动删除使用 tmpdir_factory 创建的临时目录

spring-boot - 在 Spring Boot Test 中,如何将临时文件夹映射到配置属性?

java - 安卓 : How to get view class from a view to use with instanceOf

android - 如何完成当前 Activity 并启动新的 Activity 接收方式?

ios - 将文件保存到临时目录,然后从该临时目录回调 url