導航:首頁 > 操作系統 > 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相關的資料

熱點內容
安裝包幀數文件夾 瀏覽:838
演算法可以採用哪三種方式來描述 瀏覽:281
金立m6加密晶元 瀏覽:863
為什麼ted的app沒有圖像 瀏覽:426
itext對pdf簽名 瀏覽:664
vcc如何編譯 瀏覽:412
java環境變數classpath 瀏覽:607
知乎編程入門指南 瀏覽:179
pdf如何合並文件 瀏覽:258
如何選購適合自己的雲伺服器 瀏覽:875
如何再騰訊雲伺服器做網站 瀏覽:655
類可以編譯位元組碼嗎 瀏覽:223
linux下配置java 瀏覽:891
筆記本電腦沒有解壓程序 瀏覽:807
保持強制加密要不要勾選 瀏覽:77
樂刻運動app怎麼樣 瀏覽:184
linux如何重命名文件 瀏覽:626
androidcmwap 瀏覽:371
安卓怎麼提高游戲順暢度 瀏覽:110
文本怎麼加密解密 瀏覽:352