android读写文件
一般要是在PC上建立一個虛擬機(jī),然后用DDMS的file explorer 查看虛擬手機(jī)上的文件
但是這個方法運(yùn)行速度之慢實在是不能忍,一般都是直接用手機(jī)調(diào)試,在讀寫文件的時候就有問題了,首先不能讀寫sd card上的文件,因為手機(jī)在連接PC時,是不能訪問sd card的。可以先斷開手機(jī)與PC的連接,再運(yùn)行程序??梢宰x取手機(jī)內(nèi)部硬盤上的文件,但是寫入手機(jī)內(nèi)部硬盤的文件用DDMS是看不到的,雖然寫成功了。
文件讀寫有三種方式:
1. ?資源文件只能讀不能寫
在assets和res/raw內(nèi)的文件是資源文件,只能讀。
raw內(nèi)一個文件名"out"
InputStream in = getResources().openRawResource(R.raw.out);
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
在assets內(nèi)一個文件名“text.txt”
InputStream in = getResources().getAssets().open("text.txt");
2. 讀寫sd card 文件
File path = new File("/sdcard/"); File file = new File("/sdcard/wordsize.txt");if (!path.exists()) {path.mkdir(); } if (!file.exists()) {file.createNewFile(); }BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/sdcard/wordsize.txt"), "utf-8"));在sd card的根目錄下生成wordsize文件。注意以上兩步檢測并創(chuàng)建的操作必須要有。
BufferedReader fin = new BufferedReader(new InputStreamReader(new FileInputStream("/sdcard/wordsize.txt"), "utf-8"));
注意要在Manifest中添加許可
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
3. 讀寫內(nèi)部文件
這里是指讀寫的/data/data/應(yīng)用程序名下的文件
FileOutputStream fout = m_context.openFileOutput("wordSize.txt", m_context.MODE_PRIVATE);//因為這里不是在acivity類的操作,所以要用Context對象引用
如果在activity類內(nèi)部操作,不需要m_context對象。
FileInputStream fis = m_context.openFileInput("wordSize.txt");
讀寫內(nèi)部文件,要注意必須用android提供的openFileOutput和openFileInput
總結(jié)
以上是生活随笔為你收集整理的android读写文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。