IAM是Android编程的新手
这段代码给FilenotFound异常
并通过捕获块
我应该在哪里保存我的.txt文件。

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    myCOde=findViewById(R.id.code);
    String filename="bully rap.txt";
    try {
        readCode(filename);

    } catch (Exception e) {
        myCOde.setText("file not found");
    }
}



    private void readCode(String filename) throws Exception{
    File filesDir=MainActivity.this.getFilesDir();
    File myFile=new File(filesDir,filename);

    BufferedReader br = new BufferedReader(new FileReader(myFile));

    String st;
    StringBuilder code= new StringBuilder("hello");
    while ((st = br.readLine()) != null){
     code.append(st);
     myCOde.setText(code);
    }

最佳答案

使用下面的代码并不能帮助您实现所需的功能。

File filesDir = MainActivity.this.getFilesDir();


上面的代码通常返回/data/data/{your package name}/files所在的路径。如果要访问外部文件目录,例如“下载”文件夹,则应使用以下内容。

String filesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);


此外,如果要写入外部文件目录,则可能需要在manifest.xml中添加必要的权限。

09-30 09:46