導航:首頁 > 操作系統 > androidfile讀寫

androidfile讀寫

發布時間:2022-08-19 11:57:38

android寫入txt文件

分以下幾個步驟:

  1. 首先對manifest注冊SD卡讀寫許可權

    java">AndroidManifest.xml
    <?xmlversion="1.0"encoding="utf-8"?>
    <manifestxmlns:android="

    package="com.tes.textsd"
    android:versionCode="1"
    android:versionName="1.0">
    <uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="16"/>
    <uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    <activity
    android:name="com.tes.textsd.FileOperateActivity"
    android:label="@string/app_name">
    <intent-filter>
    <actionandroid:name="android.intent.action.MAIN"/>
    <categoryandroid:name="android.intent.category.LAUNCHER"/>
    </intent-filter>
    </activity>
    </application>
    </manifest>
  2. 創建一個對SD卡中文件讀寫的類

    FileHelper.java
    /**
    *@Title:FileHelper.java
    *@Packagecom.tes.textsd
    *@Description:TODO(用一句話描述該文件做什麼)
    *@authorAlex.Z
    *@date2013-2-26下午5:45:40
    *@versionV1.0
    */
    packagecom.tes.textsd;
    importjava.io.DataOutputStream;
    importjava.io.File;
    importjava.io.FileOutputStream;
    importjava.io.FileWriter;
    importjava.io.FileInputStream;
    importjava.io.FileNotFoundException;
    importjava.io.IOException;
    importandroid.content.Context;
    importandroid.os.Environment;
    publicclassFileHelper{
    privateContextcontext;
    /**SD卡是否存在**/
    privatebooleanhasSD=false;
    /**SD卡的路徑**/
    privateStringSDPATH;
    /**當前程序包的路徑**/
    privateStringFILESPATH;
    publicFileHelper(Contextcontext){
    this.context=context;
    hasSD=Environment.getExternalStorageState().equals(
    android.os.Environment.MEDIA_MOUNTED);
    SDPATH=Environment.getExternalStorageDirectory().getPath();
    FILESPATH=this.context.getFilesDir().getPath();
    }
    /**
    *在SD卡上創建文件
    *
    *@throwsIOException
    */
    publicFilecreateSDFile(StringfileName)throwsIOException{
    Filefile=newFile(SDPATH+"//"+fileName);
    if(!file.exists()){
    file.createNewFile();
    }
    returnfile;
    }
    /**
    *刪除SD卡上的文件
    *
    *@paramfileName
    */
    publicbooleandeleteSDFile(StringfileName){
    Filefile=newFile(SDPATH+"//"+fileName);
    if(file==null||!file.exists()||file.isDirectory())
    returnfalse;
    returnfile.delete();
    }
    /**
    *寫入內容到SD卡中的txt文本中
    *str為內容
    */
    publicvoidwriteSDFile(Stringstr,StringfileName)
    {
    try{
    FileWriterfw=newFileWriter(SDPATH+"//"+fileName);
    Filef=newFile(SDPATH+"//"+fileName);
    fw.write(str);
    FileOutputStreamos=newFileOutputStream(f);
    DataOutputStreamout=newDataOutputStream(os);
    out.writeShort(2);
    out.writeUTF("");
    System.out.println(out);
    fw.flush();
    fw.close();
    System.out.println(fw);
    }catch(Exceptione){
    }
    }
    /**
    *讀取SD卡中文本文件
    *
    *@paramfileName
    *@return
    */
    publicStringreadSDFile(StringfileName){
    StringBuffersb=newStringBuffer();
    Filefile=newFile(SDPATH+"//"+fileName);
    try{
    FileInputStreamfis=newFileInputStream(file);
    intc;
    while((c=fis.read())!=-1){
    sb.append((char)c);
    }
    fis.close();
    }catch(FileNotFoundExceptione){
    e.printStackTrace();
    }catch(IOExceptione){
    e.printStackTrace();
    }
    returnsb.toString();
    }
    publicStringgetFILESPATH(){
    returnFILESPATH;
    }
    publicStringgetSDPATH(){
    returnSDPATH;
    }
    publicbooleanhasSD(){
    returnhasSD;
    }
    }
  3. 寫一個用於檢測讀寫功能的的布局

    main.xml
    <?xmlversion="1.0"encoding="utf-8"?>
    <LinearLayoutxmlns:android="

    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <TextView
    android:id="@+id/hasSDTextView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="hello"/>
    <TextView
    android:id="@+id/SDPathTextView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="hello"/>
    <TextView
    android:id="@+id/FILESpathTextView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="hello"/>
    <TextView
    android:id="@+id/createFileTextView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="false"/>
    <TextView
    android:id="@+id/readFileTextView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="false"/>
    <TextView
    android:id="@+id/deleteFileTextView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="false"/>
    </LinearLayout>
  4. 就是UI的類了

    FileOperateActivity.class
    /**
    *@Title:FileOperateActivity.java
    *@Packagecom.tes.textsd
    *@Description:TODO(用一句話描述該文件做什麼)
    *@authorAlex.Z
    *@date2013-2-26下午5:47:28
    *@versionV1.0
    */
    packagecom.tes.textsd;
    importjava.io.IOException;
    importandroid.app.Activity;
    importandroid.os.Bundle;
    importandroid.widget.TextView;
    {
    privateTextViewhasSDTextView;
    privateTextViewSDPathTextView;
    ;
    ;
    ;
    ;
    privateFileHelperhelper;
    @Override
    publicvoidonCreate(BundlesavedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    hasSDTextView=(TextView)findViewById(R.id.hasSDTextView);
    SDPathTextView=(TextView)findViewById(R.id.SDPathTextView);
    FILESpathTextView=(TextView)findViewById(R.id.FILESpathTextView);
    createFileTextView=(TextView)findViewById(R.id.createFileTextView);
    readFileTextView=(TextView)findViewById(R.id.readFileTextView);
    deleteFileTextView=(TextView)findViewById(R.id.deleteFileTextView);
    helper=newFileHelper(getApplicationContext());
    hasSDTextView.setText("SD卡是否存在:"+helper.hasSD());
    SDPathTextView.setText("SD卡路徑:"+helper.getSDPATH());
    FILESpathTextView.setText("包路徑:"+helper.getFILESPATH());
    try{
    createFileTextView.setText("創建文件:"
    +helper.createSDFile("test.txt").getAbsolutePath());
    }catch(IOExceptione){
    e.printStackTrace();
    }
    deleteFileTextView.setText("刪除文件是否成功:"
    +helper.deleteSDFile("xx.txt"));
    helper.writeSDFile("1213212","test.txt");
    readFileTextView.setText("讀取文件:"+helper.readSDFile("test.txt"));
    }
    }

② 如何在Android中從文件中讀寫字元串

1、通過File獲取文件
2、打開輸入流,讀取文件
寫文件:
1、創建文件
2、打開輸出流,寫入文件內容
示例:

12345678910111213

讀文件:String content = ""; //文件內容字元串 //通過路徑/sdcard/foo.txt打開文件 File file = new File("/sdcard/foo.txt"); try { InputStream instream = new FileInputStream(file);//讀取輸入流 InputStreamReader inputreader = new InputStreamReader(instream);//設置流讀取方式 BufferedReader buffreader = new BufferedReader(inputreader); while (( line = buffreader.readLine()) != null) { content += line + "\n";//讀取的文件內容 } }catch(Exception ex){ }

寫文件: File file = new File("/sdcard/foo.txt");// if(!file.exists()) file.createNewFile();//如果文件不存在,創建foo.txt try { OutputStream outstream = new FileOutputStream(file);//設置輸出流 OutputStreamWriter out = new OutputStreamWriter(outstream);//設置內容輸出方式 out.write("文字內容");//輸出內容到文件中 out.close(); } catch (java.io.IOException e) { e.printStackTrace(); }

③ android讀取txt文件

您好,Android的res文件夾是用來存儲資源的,可以在res文件夾下建立一個raw文件夾,放置在raw文件夾下的內容會被原樣打包,而不會被編譯成二進制文件,並且可以通過R文件進行很方便地訪問。
比如我們可以將更新信息、版權信息等放到txt文件中,然後放到raw文件中,然後很方便地進行訪問。
在raw中放入一個a.txt文件,然後就可以在Activity中使用getResources().openRawResource(R.raw.a);方法獲取一個此文件的InputStream類,而後就可以很方便地進行讀寫a.txt了。

④ Android 如何通過java代碼實現修改指定路徑文件的讀寫許可權。

請參考

publicclass MainActivity extends Activity{
publicvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String apkRoot="chmod 777 "+getPackageCodePath();
SystemManager.RootCommand(apkRoot);
}
}

當然,運行的程序本身要有root權

⑤ Android 根目錄下讀寫.txt文件

//根目錄許可權不允許,放到/data/packeg_dir下或SD卡中

packagecom.example.demo;

Filedir=Environment.getDataDirectory();//獲取data目錄
//Environment.getExternalStorageDirectory();//獲取SD卡目錄
FileoutFile=newFile(dir,"/data/com.example.demo/text.txt");//只能在自己的程序包里建立文件,這是許可權問題

⑥ android如何讀寫/data/data文件

讀寫文件,和java中沒有區別的Filefile=newFIle("文件絕對路徑");注意這里的文件路徑,windows平台下盤符是c:d:e:等android是linux內核,路徑是/開頭的其它的就是InputStreamoutputStream沒什麼區別

⑦ android中可以使用sharedpreferences類的實例完成文件讀寫操作嗎

很多時候我們開發的軟體需要向用戶提供軟體參數設置功能,例如我們常用的QQ,用戶可以設置是否允許陌生人添加自己為好友。對於軟體配置參數的保存,如果是window軟體,通常會採用ini文件進行保存;如果是 j2se應用,通常會採用properties屬性文件進行保存;如果是Android應用,Android 平台提供了一個SharedPreferences類,它是一個輕量級的存儲類,特別適合用於保存軟體配置參數。使用SharedPreferences保存數據,其背後是用xml文件存放數據,文件存放在/data/data//shared_prefs目錄下。
因為SharedPreferences背後是使用xml文件保存數據,getSharedPreferences(name,mode)方法的第一個參數用於指定該文件的名稱,名稱不用帶後綴,後綴會由Android自動加上。方法的第二個參數指定文件的操作模式,共有四種操作模式,這四種模式分別是:
Context.MODE_PRIVATE:為默認操作模式,代表該文件是私有數據,只能被應用本身訪問,在該模式下,寫入的內容會覆蓋原文件的內容,如果想把新寫入的內容追加到原文件中。可以使用Context.MODE_APPEND
Context.MODE_APPEND:模式會檢查文件是否存在,存在就往文件追加內容,否則就創建新文件。
Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用來控制其他應用是否有許可權讀寫該文件。
MODE_WORLD_READABLE:表示當前文件可以被其他應用讀取;
MODE_WORLD_WRITEABLE:表示當前文件可以被其他應用寫入。
如果希望文件被其他應用讀和寫,可以傳入:
openFileOutput("123.txt", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

android有一套自己的安全模型,當應用程序(.apk)在安裝時系統就會分配給它一個userid,當該應用要去訪問其它資源(比如文件),就需要userid匹配。默認情況下,任何應用創建的文件,sharedpreferences資料庫都應該是私有的(位於/data/data //files),其它程序無法訪問。除非在創建時指定了Context.MODE_WORLD_READABLE或者 Context.MODE_WORLD_WRITEABLE ,只有這樣其它程序才能正確訪問。

另外Activity還提供了另一個getPreferences(mode)方法操作SharedPreferences,這個方法默認使用當前類不帶包名的類名作為文件的名稱。
如果訪問其它應用中的Preference,前提條件是該preference創建時指定了Context.MODE_WORLD_READABLE或 者Context.MODE_WORLD_WRITEABLE許可權。如有個為cn.itcast.action的應用使用下面語句創建了preference:
getSharedPreferences("123", Context.MODE_WORLD_READABLE);
其它應用要訪問上面應用的preference,首先需要創建上面應用的Context,然後通過Context 訪問preference ,訪問preference時會在應用所在包下的shared_prefs目錄找到preference。如果不通過創建Context訪問其他應用的preference,可以以讀取xml文件方式直接訪問其他應用preference對應的xml文件,如:
File xmlFile = new File(「/data/data//shared_prefs/itcast.xml」);//應替換成應用的包名

⑧ 如何在安卓/data目錄下進行文件的讀寫操作

/** * 存儲文件 * @param context 設備上下文 * @param btimap 點陣圖 * @param bitmapName 點陣圖名稱 * @return */ @SuppressLint("WorldWriteableFiles") @SuppressWarnings("deprecation") private static boolean saveBitmap( Context context , Bitmap btimap , String bitmapName ) { try { FileOutputStream fOut = contextpress(Bitmap.CompressFormat.PNG, 100, fOut); fOut.flush(); return true; } catch (Exception e) { e.printStackTrace(); } return false; } 以上代碼僅供參考。 通過以上代碼可以在data文件夾下的應用的包名文件夾下新建文件。 希望能夠幫到你

⑨ android 讀寫文件需要哪些許可權

<!--往sdcard中寫入數據的許可權 --><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission><!--在sdcard中創建/刪除文件的許可權 --><uses-permission android:name="android.permission.MOUNT_U

  1. android中的apk必須簽名

    這種簽名不是基於權威證書的,不會決定某個應用允不允許安裝,而是一種自簽名證書。

    重要的是,android系統有的許可權是基於簽名的。比如:system等級的許可權有專門對應的簽名,簽名不對,許可權也就獲取不到。默認生成的APK文件是debug簽名的。

  2. 獲取system許可權時用到的簽名,見:如何使Android應用程序獲取系統許可權。基於UserID的進程級別的安全機。這種簽名不是基於權威證書的,不會決定某個應用允不允許安裝,而是一種自簽名證書。重要的是,android系統有的許可權是基於簽名的。

閱讀全文

與androidfile讀寫相關的資料

熱點內容
手機怎麼設置不解壓 瀏覽:109
崇石是誰演的 瀏覽:827
免費影視觀看網站入口 瀏覽:877
為什麼伺服器會出現很多藍屏 瀏覽:34
三國種馬收了何皇後 瀏覽:344
思甜APP怎麼樣 瀏覽:525
床戲美國 瀏覽:763
醉猴拳電影在線觀看 瀏覽:832
程序員在線教育 瀏覽:986
有部電影人可以穿牆 瀏覽:656
丁巴度電影有哪些 瀏覽:49
歐文電影叫什麼名字 瀏覽:498
雲伺服器操作過程 瀏覽:689
python自動提取參數 瀏覽:161
linuxjetty查看版本 瀏覽:689
mysql存儲數組php 瀏覽:482
舒淇六部 瀏覽:901
穿越影視世界收女主的小數 瀏覽:852
胸很大電影 瀏覽:925
台灣催淚老電影推薦 瀏覽:924