【发布时间】:2015-04-03 08:42:13
【问题描述】:
我正在编写一个需要缓存一些文件的应用程序。它需要缓存的内容是使用 Reader 阅读器或使用 String 提供的。 当我使用必要的参数调用 writeToCache 函数时,它不会将文件写入缓存目录。我究竟做错了什么?? (使用 FX 浏览器我检查了目录 /SYSTEM(手机已植根)/data/data/com.package/cache 它包含文件,但不包含具有指定文件名的文件)
顺便说一句,System.out.println(file.getPath()) 输出正确的路径!
这是编写 Reader 对象的代码:
/**
*
* @param reader The reader that contains the data that is used to parse the file
* @param fileName the filename WITH extension
*/
public void saveToCache(final Reader reader, String fileName){
final File file = new File(context.getApplicationContext().getCacheDir(), fileName);
System.out.println("file.getPath() = " + file.getPath());
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if(reader == null){
System.err.println("reader == null!!");
}
Thread writeCache = new Thread(){
@Override
public void run(){
try {
OutputStream outStream;
outStream = new BufferedOutputStream(new FileOutputStream(file), 8 * 1024);
outStream.write(reader.read());
outStream.flush();
outStream.close();
Log.d("cacheManager", String.valueOf(reader.read()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
System.out.println("savedItemToCache");
}
这是编写String对象的代码:
/**
*
* @param content The content that needs to be written
* @param fileName the filename WITH extension
*/
public void saveToCache(final String content, String fileName){
final File file = new File(context.getApplicationContext().getCacheDir(), fileName);
System.out.println("file.getPath() = " + file.getPath());
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if(content == null){
System.err.println("content == null");
}
Thread writeCache = new Thread(){
@Override
public void run(){
try {
OutputStream outStream;
outStream = new BufferedOutputStream(new FileOutputStream(file), 8 * 1024);
outStream.write(content.getBytes(), 0, content.getBytes().length);
outStream.flush();
outStream.close();
Log.d("cacheManager", String.valueOf(content.getBytes()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
System.out.println("savedItemToCache");
}
【问题讨论】:
-
FX 文件资源管理器无法访问您应用的内存。只有当您的设备已植根时,才有机会。但是使用 File.exists() 您可以轻松检查文件是否存在。
-
@greenapps 这就是为什么我将 (with root) 放在上面的路径中;-)
-
我看到了,但这并没有让我认为您的设备已植根。
-
Log.d("cacheManager", String.valueOf(reader.read()));。你看到这个日志语句了吗? -
是的,我已经更新了问题