我是 Android 編程新手,這段代碼給出了 FilenotFound 異常,并通過 catch 塊,我應該在哪里保存我的 .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); }
1 回答

慕斯709654
TA貢獻1840條經驗 獲得超5個贊
使用下面的代碼不會幫助你實現你想要的。
File filesDir = MainActivity.this.getFilesDir();
上面的代碼通常返回/data/data/{your package name}/files
. 如果您想訪問外部文件目錄,就像下載文件夾一樣,您應該使用如下所示的內容。
String filesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
此外,如果您要寫入外部文件目錄,您可能需要在manifest.xml中添加必要的權限
添加回答
舉報
0/150
提交
取消