android读写文件
一般要是在PC上建立一個虛擬機,然后用DDMS的file explorer 查看虛擬手機上的文件
但是這個方法運行速度之慢實在是不能忍,一般都是直接用手機調試,在讀寫文件的時候就有問題了,首先不能讀寫sd card上的文件,因為手機在連接PC時,是不能訪問sd card的。可以先斷開手機與PC的連接,再運行程序。可以讀取手機內部硬盤上的文件,但是寫入手機內部硬盤的文件用DDMS是看不到的,雖然寫成功了。
文件讀寫有三種方式:
1. ?資源文件只能讀不能寫
在assets和res/raw內的文件是資源文件,只能讀。
raw內一個文件名"out"
InputStream in = getResources().openRawResource(R.raw.out);
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
在assets內一個文件名“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文件。注意以上兩步檢測并創建的操作必須要有。
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. 讀寫內部文件
這里是指讀寫的/data/data/應用程序名下的文件
FileOutputStream fout = m_context.openFileOutput("wordSize.txt", m_context.MODE_PRIVATE);//因為這里不是在acivity類的操作,所以要用Context對象引用
如果在activity類內部操作,不需要m_context對象。
FileInputStream fis = m_context.openFileInput("wordSize.txt");
讀寫內部文件,要注意必須用android提供的openFileOutput和openFileInput
總結
以上是生活随笔為你收集整理的android读写文件的全部內容,希望文章能夠幫你解決所遇到的問題。