在安卓应用包中指定自定义文件夹地址



我想在我的安卓应用程序中添加一个文本文件,这样就没有人可以重新编辑或删除它。我正在使用BufferedReaderFileReader函数来访问它,但是我在提供文件路径时遇到了问题,因为它显示了我的笔记本电脑路径,当应用程序安装在手机上时,该路径会发生变化。因此,需要一些更好的选项来指定文件的路径。我已经创建了一个文件夹,src应用程序并使用安卓工作室进行编码。

只需将您的文本文件放在 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>

安卓代码

 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