2017-01-10 75 views
0

我想在我的android應用程序中添加一個文本文件,以便任何人都不能重新編輯或刪除它。我正在使用BufferedReaderFileReader函數來訪問它,但是我在給出文件路徑時遇到了問題,因爲它顯示了我的筆記本電腦路徑,當在手機上安裝應用程序時它將會改變。所以需要一些更好的選項來指定文件的路徑。我在應用程序的src中創建了一個文件夾,並使用android studio編碼。在Android應用程序包中指定自定義文件夾地址

回答

0

只要把Android的 資產文件夾中的文本文件中引用這個答案的例子 https://stackoverflow.com/a/5771369/5409229

示例代碼

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:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="@string/hello" 
/> 
</LinearLayout> 

的Android代碼

package com.javasamples; 

//reading an embedded RAW data file 

import android.app.Activity; 
import android.os.Bundle; 
import android.widget.Toast; 
import java.io.*; 

public class FileDemo1 extends Activity { 

@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.main); 
try { 
    PlayWithRawFiles(); 
} catch (IOException e) { 
    Toast.makeText(getApplicationContext(), 
       "Problems: " + e.getMessage(), 1).show(); 
} 
    }// onCreate 

public void PlayWithRawFiles() throws IOException {  
String str=""; 
StringBuffer buf = new StringBuffer();   
InputStream is = this.getResources().openRawResource(R.myfolder.text_file); 
BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
if (is!=null) {       
    while ((str = reader.readLine()) != null) { 
     buf.append(str + "\n"); 
    }    
}  
is.close(); 
Toast.makeText(getBaseContext(), 
     buf.toString(), Toast.LENGTH_LONG).show();    


}// PlayWithSDFiles 

} // FilesDemo4 
+0

@錢德拉曼帕蒂爾檢查我f這就是你想要的,如果是的話接受答案 –

+1

這工作,但只需要將「R.drawable.my_base_data」行更改爲「R.myfolder.text_file」作爲可繪製文件夾不存儲.txt文件,所以我在res文件夾中創建了一個新目錄。 非常感謝。 –

+0

@ chandraman-patil然後接受答案 –

相關問題