导航:首页 > 操作系统 > androidlistfiles

androidlistfiles

发布时间:2022-05-13 02:25:34

‘壹’ android Studio 如何遍历openFileOutput保存的文件

File file = new File(SYS_FILE_PATH);

if( file.isDirectory() ) {

File [] fileArray = file.listFiles();
if(null != fileArray && 0 != fileArray.length) {
for(int i = 0; i < fileArray.length; i++) {
// fileArray[i].getName();
Log.i("MainActivity.java", fileArray[i].getName());
}
}

}

android读取指定文件夹里的所有文件

‘贰’ android开发怎样获得文件夹中的所有文件

有的时候程序需要去对android的指定目录或者全局目录进行遍历获取其中的文件,但是获取文件的时候可能会遇到无法列出文件夹中的文件的问题,这就是出现的问题,对于某个子文件夹进行获取listFiles()的时候返回为NULL,也就是不允许列出文件夹中内容。
这个是由于android中的安全机制的缘故,由于android继承了linux系统的传统,对于某个特定的目录有用户的权限,一共分为三种--可读,可写,可执行;虽然说可以设置某个特定的目录的权限,但是对于目录里面的子目录和子文件都可以进行权限的设置,也就是说出了根目录权限之外,子目录本身的权限也决定了子目录可否访问,这一点需要清楚了解,所以在判断完了是否是目录之外,还需要在进行listFiles()获取File[]数据后判断获取的数组是否为空,如果为空的话,文件夹是不可访问的。样例代码如下:
01 package net.nowamagic.file;
02 import java.io.File;
03 import java.util.ArrayList;
04 import java.util.HashMap;
05 import java.util.Map;
06 import android.util.Log;
07 /**
08 * @author
09 * function 用于扫描SD卡上的文件
10 *
11 */
12 public class FileScan {
13
14 private static final String TAG = "FileScan";
15 public HashMap<String, String> getMusicListOnSys(File file) {
16
17 //从根目录开始扫描
18 Log.i(TAG, file.getPath());
19 HashMap<String, String> fileList = new HashMap<String, String>();
20 getFileList(file, fileList);
21 return fileList;
22 }
23
24 /**
25 * @param path
26 * @param fileList
27 * 注意的是并不是所有的文件夹都可以进行读取的,权限问题
28 */
29 private void getFileList(File path, HashMap<String, String> fileList){
30 //如果是文件夹的话
31 if(path.isDirectory()){
32 //返回文件夹中有的数据
33 File[] files = path.listFiles();
34 //先判断下有没有权限,如果没有权限的话,就不执行了
35 if(null == files)
36 return;
37
38 for(int i = 0; i < files.length; i++){
39 getFileList(files[i], fileList);
40 }
41 }
42 //如果是文件的话直接加入
43 else{
44 Log.i(TAG, path.getAbsolutePath());
45 //进行文件的处理
46 String filePath = path.getAbsolutePath();
47 //文件名
48 String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
49 //添加
50 fileList.put(fileName, filePath);
51 }
52 }
53
54 }

出处:http://www.nowamagic.net/librarys/veda/detail/1481

‘叁’ android 怎样遍历文件夹下的文件(文件夹下可能还有文件夹)

java代码:
import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ShuosouwenjianActivity extends Activity implements OnClickListener {

private File file;
private String path;
private String info;
private String key; //关键字
private TextView result; // 显示结果
private EditText et; // 编辑view
private Button search_btn; // button view

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

result = (TextView)findViewById(R.id.TextView_Result);
et = (EditText)findViewById(R.id.key);
search_btn = (Button)findViewById(R.id.button_search);
// file = new File(Environment.getExternalStorageDirectory().getPath());
file = new File("/sdcard/");
info = getString(R.string.info);

search_btn.setOnClickListener(this);
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
path = "";
result.setText("");
key = et.getText().toString();
BrowserFile(file);
}

public void BrowserFile(File fileold) {
if (key.equals("")) {
Toast.makeText(this, getString(R.string.pleaseInput), Toast.LENGTH_LONG).show();
} else {
search(fileold);
if (result.getText().equals("")) {
Toast.makeText(this, getString(R.string.notFound), Toast.LENGTH_SHORT).show();
}
}
}

private void search(File fileold)
{
try{
File[] files=fileold.listFiles();
if(files.length>0)
{
for(int j=0;j<files.length;j++)
{
if(!files[j].isDirectory())
{
if(files[j].getName().indexOf(key)> -1)
{
path += "\n" + files[j].getPath();
result.setText(info+path);

//shuju.putString(files[j].getName().toString(),files[j].getPath().toString());
}
}
else{
this.search(files[j]);
}
}
}
}
catch(Exception e)
{

}
}
}

MAIN.XML代码:
<?xml version="1.0" encoding="utf-8"?>
< AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/widget0"
>

< Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button_search"
android:layout_x="253px"
android:layout_y="5px"
android:text="@string/toSearch"
/>
< EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/key"
android:text="821077962.db"

/>
<TextView
android:layout_width="fill_parent"
android:layout_height="370px"
android:id="@+id/TextView_Result"
android:layout_x="0px"
android:layout_y="60px"
/>
< /AbsoluteLayout>
strings.xml代码:
<?xml version="1.0" encoding="utf-8"?>
< resources>
< string name="hello">Hello World, Activity07!</string>
< string name="app_name">文件搜索</string>
< string name="toSearch">搜索</string>
< string name="info">系统SDCard目录文件路径:\n</string>
< string name="pleaseInput">请输入关键字!</string>
< string name="notFound">SD卡中没有相关文件!!</string>
< string name="pathError">读取路径出错!!</string>
< /resources>

‘肆’ android怎么获取一个文件的地址

跟java里获取当前本地文件、文件夹,,点击文件夹,显示该文件夹下的文件和文件夹,是没有区别的啊,唯一就是在文件夹上添加监听事件,然后获取对象就是了……

activity :
package com.hundsun.zhoujl.android;

import java.io.File;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class Test_fileActivity extends ListActivity {

private ArrayList<String> items = null;

private ArrayList<String> paths = null;

private String rootPath = "/";

private TextView mPath;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

mPath = (TextView)findViewById(R.id.mPath);

mPath.setTextColor(Color.RED);

getFileDir(rootPath);

}

private void getFileDir(String filePath) {

mPath.setText(filePath);

items = new ArrayList<String>();

paths = new ArrayList<String>();

File file = new File(filePath);

File[] files = file.listFiles();

if(!filePath.equals(rootPath)) {

items.add("Back To " + rootPath);

paths.add(rootPath);

items.add("Back to ../");

paths.add(file.getParent());

}

for(File fileTemp :files) {

items.add(fileTemp.getName());

paths.add(fileTemp.getPath());

}

ArrayAdapter<String> adapter = new ArrayAdapter<String>(Test_fileActivity.this,R.layout.file_now,items);

setListAdapter(adapter);

}

@Override

protected void onListItemClick(ListView l, View v, int position, long id) {

File file = new File(paths.get(position));

if(file.canRead()) {

if(file.isDirectory()) {

getFileDir(paths.get(position));

}else {

new AlertDialog.Builder(this)

.setTitle("Message")

.setMessage("["+file.getName() + "] is a file")

.setPositiveButton("ok", new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

}

}).show();

}

}else {

new AlertDialog.Builder(this)

.setTitle("Message")

.setMessage("权限不足~")

.setPositiveButton("ok", new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

}

}).show();

}

}

}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="@+id/mPath"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<ListView

android:id="@android:id/list"

android:layout_width="fill_parent"

android:layout_height="wrap_content"
>
</ListView>

</LinearLayout>

file_now.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="20px"
android:textSize="14sp"
>

</TextView>

‘伍’ android开发文件缓存在什么位置,可以在应用程序中清除。

android开发文件缓存的默认位置一般是在android/data目录下,比如kindle(1st)是在/mnt/sdcard/Android/data目录下,魅族是在/sdcard/Android/data目录下。
将缓存在应用程序中清除:
打开关闭使用缓存,一共有五个种类
//优先使用缓存:
WebView.getSettings().setCacheMod
(WebSettings.LOAD_CACHE_ELSE_NETWORK);
//不使用缓存:
WebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
在退出应用的时候加上如下代码
File file = CacheManager.getCacheFileBaseDir();
if (file != null && file.exists() && file.isDirectory()) {
for (File item : file.listFiles()) {
item.delete(); }
file.delete(); }
context.deleteDatabase("WebView.db");
context.deleteDatabase("WebViewCache.db");
以上方法均可实现。

‘陆’ android中怎么获取指定目录下的文件夹

参考如下代码:
package com.Aina.Android;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class Test_ListFile extends ListActivity {
/** Called when the activity is first created. */
private List<String> items = null;//存放名称
private List<String> paths = null;//存放路径
private String rootPath = "/";
private TextView tv;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) this.findViewById(R.id.TextView);
this.getFileDir(rootPath);//获取rootPath目录下的文件.
}

public void getFileDir(String filePath) {
try{
this.tv.setText("当前路径:"+filePath);// 设置当前所在路径
items = new ArrayList<String>();
paths = new ArrayList<String>();
File f = new File(filePath);
File[] files = f.listFiles();// 列出所有文件
// 如果不是根目录,则列出返回根目录和上一目录选项
if (!filePath.equals(rootPath)) {
items.add("返回根目录");
paths.add(rootPath);
items.add("返回上一层目录");
paths.add(f.getParent());
}
// 将所有文件存入list中
if(files != null){
int count = files.length;// 文件个数
for (int i = 0; i < count; i++) {
File file = files[i];
items.add(file.getName());
paths.add(file.getPath());
}
}

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
this.setListAdapter(adapter);
}catch(Exception ex){
ex.printStackTrace();
}

}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String path = paths.get(position);
File file = new File(path);
//如果是文件夹就继续分解
if(file.isDirectory()){
this.getFileDir(path);
}else{
new AlertDialog.Builder(this).setTitle("提示").setMessage(file.getName()+" 是一个文件!").setPositiveButton("OK", new DialogInterface.OnClickListener(){

public void onClick(DialogInterface dialog, int which) {

}

}).show();
}
}

}

‘柒’ android使用listfiles()获得文件并将其存储至File[] files后无法获得files.length

读取的SD卡目录是否存在,如果存在的话,请看一下在AndroidManifest.xml里是否添加了读取sd卡的权限

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

log要截右边的部分,把滚动条滚到右边去再截,不然看不到有用的信息

‘捌’ Android的权限都有哪些

(一)linux文件系统上的权限
-rwxr-x--x system system 4156 2010-04-30 16:13 test.apk
代表的是相应的用户/用户组及其他人对此文件的访问权限,与此文件运行起来具有的权限完全不相关。
比如上面的例子只能说明system用户拥有对此文件的读写执行权限;system组的用户对此文件拥有读、执行权限;其他人对此文件只具有执行权限。
而test.apk运行起来后可以干哪些事情,跟这个就不相关了。
千万不要看apk文件系统上属于system/system用户及用户组,或者root/root用户及用户组,就认为apk具有system或root权限
(二)Android的权限规则
(1)Android中的apk必须签名
这种签名不是基于权威证书的,不会决定某个应用允不允许安装,而是一种自签名证书。
重要的是,android系统有的权限是基于签名的。比如:system等级的权限有专门对应的签名,签名不对,权限也就获取不到。
默认生成的APK文件是debug签名的。
获取system权限时用到的签名,见:如何使Android应用程序获取系统权限
(2)基于UserID的进程级别的安全机制
大家都知道,进程有独立的地址空间,进程与进程间默认是不能互相访问的,是一种很可靠的保护机制。
Android通过为每一个安装在设备上的包(apk)分配唯一的linux userID来实现,名称为"app_"加一个数字,比如app_43
不同的UserID,运行在不同的进程,所以apk之间默认便不能相互访问。
Android提供了如下的一种机制,可以使两个apk打破前面讲的这种壁垒。
在AndroidManifest.xml中利用sharedUserId属性给不同的package分配相同的userID,通过这样做,两个package可以被当做同一个程序,
系统会分配给两个程序相同的UserID。当然,基于安全考虑,两个package需要有相同的签名,否则没有验证也就没有意义了。
(这里补充一点:并不是说分配了同样的UserID,两程序就运行在同一进程, 下面为PS指令摘取的,
显然,system、app_2分别对应的两个进程的PID都不同,不知Android到底是怎样实现它的机制的)
User PID PPID
system 953 883 187340 55052 ffffffff afe0cbcc S system_server
app_2 1072 883 100264 19564 ffffffff afe0dcc4 S com.android.inputmethod.
system 1083 883 111808 23192 ffffffff afe0dcc4 S android.process.omsservi
app_2 1088 883 156464 45720 ffffffff afe0dcc4 S android.process.acore
(3)默认apk生成的数据对外是不可见的
实现方法是:Android会为程序存储的数据分配该程序的UserID。
借助于Linux严格的文件系统访问权限,便实现了apk之间不能相互访问似有数据的机制。
例:我的应用创建的一个文件,默认权限如下,可以看到只有UserID为app_21的程序才能读写该文件。
-rw------- app_21 app_21 87650 2000-01-01 09:48 test.txt
如何对外开放?
<1> 使用MODE_WORLD_READABLE and/or MODE_WORLD_WRITEABLE 标记。
When creating a new file with getSharedPreferences(String, int), openFileOutput(String, int), or openOrCreateDatabase(String, int, SQLiteDatabase.CursorFactory), you can use the MODE_WORLD_READABLE and/or MODE_WORLD_WRITEABLE flags to allow any other package to read/write the file. When setting these flags, the file is still owned by your application, but its global read and/or write permissions have been set appropriately so any other application can see it.
(4)AndroidManifest.xml中的显式权限声明
Android默认应用是没有任何权限去操作其他应用或系统相关特性的,应用在进行某些操作时都需要显式地去申请相应的权限。
一般以下动作时都需要申请相应的权限:
A particular permission may be enforced at a number of places ring your program's operation:
At the time of a call into the system, to prevent an application from executing certain functions.
When starting an activity, to prevent applications from launching activities of other applications.
Both sending and receiving broadcasts, to control who can receive your broadcast or who can send a broadcast to you.
When accessing and operating on a content provider.
Binding or starting a service.
在应用安装的时候,package installer会检测该应用请求的权限,根据该应用的签名或者提示用户来分配相应的权限。
在程序运行期间是不检测权限的。如果安装时权限获取失败,那执行就会出错,不会提示用户权限不够。
大多数情况下,权限不足导致的失败会引发一个 SecurityException, 会在系统log(system log)中有相关记录。
(5)权限继承/UserID继承
当我们遇到apk权限不足时,我们有时会考虑写一个linux程序,然后由apk调用它去完成某个它没有权限完成的事情,很遗憾,这种方法是行不通的。
前面讲过,android权限是经营在进程层面的,也就是说一个apk应用启动的子进程的权限不可能超越其父进程的权限(即apk的权限),
即使单独运行某个应用有权限做某事,但如果它是由一个apk调用的,那权限就会被限制。
实际上,android是通过给子进程分配父进程的UserID实现这一机制的。
(三)常见权限不足问题分析
首先要知道,普通apk程序是运行在非root、非system层级的,也就是说看要访问的文件的权限时,看的是最后三位。
另外,通过system/app安装的apk的权限一般比直接安装或adb install安装的apk的权限要高一些。
言归正传,运行一个android应用程序过程中遇到权限不足,一般分为两种情况:
(1)Log中可明显看到权限不足的提示。
此种情况一般是AndroidManifest.xml中缺少相应的权限设置,好好查找一番权限列表,应该就可解决,是最易处理的情况。
有时权限都加上了,但还是报权限不足,是什么情况呢?
Android系统有一些API及权限是需要apk具有一定的等级才能运行的。
比如 SystemClock.setCurrentTimeMillis()修改系统时间,WRITE_SECURE_SETTINGS权限好像都是需要有system级的权限才行。
也就是说UserID是system.
(2)Log里没有报权限不足,而是一些其他Exception的提示,这也有可能是权限不足造成的。
比如:我们常会想读/写一个配置文件或其他一些不是自己创建的文件,常会报java.io.FileNotFoundException错误。
系统认为比较重要的文件一般权限设置的也会比较严格,特别是一些很重要的(配置)文件或目录。

-r--r----- bluetooth bluetooth 935 2010-07-09 20:21 dbus.conf
drwxrwx--x system system 2010-07-07 02:05 data
dbus.conf好像是蓝牙的配置文件,从权限上来看,根本就不可能改动,非bluetooth用户连读的权利都没有。
/data目录下存的是所有程序的私有数据,默认情况下android是不允许普通apk访问/data目录下内容的,通过data目录的权限设置可知,其他用户没有读的权限。
所以adb普通权限下在data目录下敲ls命令,会得到opendir failed, Permission denied的错误,通过代码file.listfiles()也无法获得data目录下的内容。

‘玖’ android获取本地文件名字

我写了个例子,你看能用吗?

package com.dragonred.android.utils;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.util.Log;

public final class FileUtils {

public final static String PACKAGE_PATH = "com.dragonred.android";
// public final static String LOG_FILE_NAME = "smartprint.txt";
// public final static String LOG_FILE_PATH = STORE_DIRECTORY_PATH + File.separatorChar + LOG_FILE_NAME;

/**
* read key value from preference by key name
*
* @param context
* @param keyName
* @return
*/
public final static String readPreperence(Context context, String keyName) {
SharedPreferences settings = context.getSharedPreferences(
PACKAGE_PATH, 0);
return settings.getString(keyName, "");
}

/**
* write key name and key value into preference
*
* @param context
* @param keyName
* @param keyValue
*/
public final static void writePreperence(Context context, String keyName,
String keyValue) {
SharedPreferences settings = context.getSharedPreferences(
PACKAGE_PATH, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(keyName, keyValue);
editor.commit();
}

/**
* delete key from preference by key name
*
* @param context
* @param keyName
*/
public final static void deletePreperence(Context context, String keyName) {
SharedPreferences settings = context.getSharedPreferences(
PACKAGE_PATH, 0);
SharedPreferences.Editor editor = settings.edit();

editor.remove(keyName);
editor.commit();
}

public final static String getContextFilePath(Context context, String fileName) {
return context.getFilesDir().getAbsolutePath() + File.separatorChar + fileName;
}

public final static boolean existContextFile(Context context, String fileName) {
String filePath = context.getFilesDir().getAbsolutePath() + File.separatorChar + fileName;
Log.d("filePath", filePath);

File file = new File(filePath);
if (file.exists()) {
return true;
}
return false;
}

public final static void saveContextFile(Context context, String fileName, String content) throws Exception {
FileOutputStream outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
outputStream.write(content.getBytes());
outputStream.close();
}

public final static void saveAppendContextFile(Context context, String fileName, String content) throws Exception {
FileOutputStream outputStream = context.openFileOutput(fileName, Context.MODE_APPEND);
outputStream.write(content.getBytes());
outputStream.close();
}

public final static void deleteContextFile(Context context, String fileName) throws Exception {
context.deleteFile(fileName);
}

public final static String readContextFile(Context context, String fileName) throws Exception {
FileInputStream inputStream = context.openFileInput(fileName);
byte[] buffer = new byte[1024];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int len = -1;
while ((len = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
byte[] data = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
inputStream.close();
return new String(data);
}

/**
* delete file or folders
* @param file
*/
public final static void deleteFile(File file) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++) {
deleteFile(files[i]);
}
}
file.delete();
} else {
Log.d("deleteFile", "The file or directory does not exist!");
}
}

/**
* make directory on SD card
* @param dirPath
* @return
*/
public final static boolean makeDir(String dirPath) {
File dir = new File(dirPath);
if(!dir.isDirectory()) {
if (dir.mkdirs()) {
return true;
}
} else {
return true;
}
return false;
}

/**
* write log file
* @param filePath
* @param tag
* @param content
*/
public final static void writeLog(String filePath, String tag, String content) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String logDateTime = sdf.format(new Date());
writeFileByAppend(filePath, logDateTime + "---[" + tag + "]---" + content + "\n");
}

/**
* write file by append mode
* @param filePath
* @param content
*/
public final static void writeFileByAppend(String filePath, String content) {
// FileWriter writer = null;
// try {
// writer = new FileWriter(filePath, true);
// writer.write(content);
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// try {
// writer.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
RandomAccessFile randomFile = null;
try {
randomFile = new RandomAccessFile(filePath, "rw");
long fileLength = randomFile.length();
randomFile.seek(fileLength);
randomFile.write(content.getBytes());

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// BufferedWriter out = null;
// try {
// out = new BufferedWriter(new OutputStreamWriter(
// new FileOutputStream(filePath, true), "UTF-8"));
// out.write(content);
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// try {
// out.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }

}

/**
* write file by overwrite mode
* @param filePath
* @param content
*/
public final static void writeFile(String filePath, String content) {
// FileWriter writer = null;
// try {
// writer = new FileWriter(filePath, true);
// writer.write(content);
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// try {
// writer.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(filePath, false), "UTF-8"));
out.write(content);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* check SD card whether or not exist
* @param context
* @return
*/
public final static boolean checkSDCard(Context context) {
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
return true;
} else {
// Toast.makeText(context, "Please check your SD card! ",
// Toast.LENGTH_SHORT).show();
return false;
}
}

/**
* read last line from file
* @param filePath
* @return
*/
public final static String readLastLinefromFile(String filePath) {
RandomAccessFile raf = null;
try {
File file = new File(filePath);
if (!file.exists()) {
return null;
}

raf = new RandomAccessFile(filePath, "r");
long len = raf.length();
if (len == 0L) {
return "";
} else {
long pos = len - 1;
while (pos > 0) {
pos--;
raf.seek(pos);
if (raf.readByte() == '\n') {
break;
}
}
if (pos == 0) {
raf.seek(0);
}
byte[] bytes = new byte[(int) (len - pos)];
raf.read(bytes);
return new String(bytes);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (raf != null) {
try {
raf.close();
} catch (Exception e2) {
}
}
}
return null;
}
}

‘拾’ android 应用程序开发中,清除缓存的功能怎么做

android开发文件缓存的默认位置一般是在android/data目录下,比如kindle(1st)是在/mnt/sdcard/Android/data目录下,魅族是在/sdcard/Android/data目录下。
将缓存在应用程序中清除:
打开关闭使用缓存,一共有五个种类
//优先使用缓存:
WebView.getSettings().setCacheMod
(WebSettings.LOAD_CACHE_ELSE_NETWORK);
//不使用缓存:
WebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
在退出应用的时候加上如下代码
File file = CacheManager.getCacheFileBaseDir();
if (file != null && file.exists() && file.isDirectory()) {
for (File item : file.listFiles()) {
item.delete(); }
file.delete(); }
context.deleteDatabase("WebView.db");
context.deleteDatabase("WebViewCache.db");
以上方法均可实现。

阅读全文

与androidlistfiles相关的资料

热点内容
云服务器打开f8指令 浏览:241
盈透证券加密币 浏览:72
阿里云服务器初始密码怎么修改 浏览:266
服务器怎么设定公用网络 浏览:97
程序员自己尝尿检测出糖尿病 浏览:592
打印添加pdf 浏览:932
苹果解压专家账号 浏览:842
度晓晓app为什么关闲 浏览:228
net文件是伪编译码吗 浏览:149
伴随矩阵的matlab编程 浏览:63
单片机和h桥是什么意思 浏览:314
51单片机光控设计论文 浏览:653
涡旋式压缩机无油 浏览:729
企业网搭建及应用pdf 浏览:744
symanteclinux 浏览:878
程序员朋友化妆改造 浏览:493
应用被加密但不知道密码 浏览:586
百度云黑马android 浏览:773
java格式化long 浏览:893
汽车如何加密文档 浏览:625