我试图在一个 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/