如何在android中从手机内存中读取文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2200545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:55:58  来源:igfitidea点击:

How to read file from phone's internal memory in android?

androidmemoryreadfile

提问by rob

I have downloaded a file from HttpConnectionusing the FileOutputStreamin android and now its being written in phone's internal memory on path as i found it in File Explorer

我已经从HttpConnection使用FileOutputStreamandroid下载了一个文件,现在它被写入手机的内存中的路径,因为我在File Explorer

/data/data/com.example.packagename/files/123.ics

/data/data/com.example.packagename/files/123.ics

Now, I want to open & read the file content from phone's internal memory to UI. I tried to do it by using the FileInputStream, I have given just filename with extension to open it but I am not sure how to mention the file path for file in internal memory,as it forces the application to close.

现在,我想打开并将文件内容从手机内存读取到 UI。我尝试使用FileInputStream,我只给出了带有扩展名的文件名来打开它,但我不确定如何提及内部存储器中文件的文件路径,因为它会强制应用程序关闭。

Any suggestions?

有什么建议?



This is what I am doing:

这就是我正在做的:

try
{               
  FileInputStream fileIn;       
  fileIn = openFileInput("123.ics");
  InputStream in = null;
  EditText Userid = (EditText) findViewById(R.id.user_id);
  byte[] buffer = new byte[1024];
  int len = 0;
  while ( (len = in.read(buffer)) > 0 )         
  {     
     Userid.setText(fileIn.read(buffer, 0, len));
  }                    
  fileIn.close();                       
} catch (FileNotFoundException e)
{
   e.printStackTrace();
}
catch (IOException e)
{   
    e.printStackTrace();
}

回答by user606669

String filePath = context.getFilesDir().getAbsolutePath();//returns current directory.
File file = new File(filePath, fileName);

Similar post here 

read file from phone memory

从手机内存中读取文件

回答by CommonsWare

If the file is where you say it is, and your application is com.example.packagename, then calling openFileInput("123.ics");will return you a FileInputStreamon the file in question.

如果文件在您所说的位置,而您的应用程序是com.example.packagename,则调用openFileInput("123.ics");将返回FileInputStream有关文件的a 。

Or, call getFilesDir()to get a Fileobject pointing to /data/data/com.example.packagename/files, and work from there.

或者,调用getFilesDir()以获取File指向的对象/data/data/com.example.packagename/files,然后从那里开始工作。

回答by dax

I am using this code to open file in internal storage. i think i could help.

我正在使用此代码在内部存储中打开文件。我想我可以帮忙。

File str = new File("/data/data/com.xlabz.FlagTest/files/","hello_file.xml");