Java Android:如何将文件写入内部存储
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44587187/
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
Android: how to write a file to internal storage
提问by delca85
I am developing a simple android application and I need to write a text file in internal storage device. I know there are a lot of questions (and answers) about this matter but I really cannot understand what I am doing in the wrong way.
我正在开发一个简单的 android 应用程序,我需要在内部存储设备中写入一个文本文件。我知道关于这件事有很多问题(和答案),但我真的无法理解我做错了什么。
This is the piece of code I use in my activity in order to write the file:
这是我在活动中用于编写文件的一段代码:
public void writeAFile(){
String fileName = "myFile.txt";
String textToWrite = "This is some text!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(fileName , Context.MODE_PRIVATE);
outputStream.write(textToWrite.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I really cannot understand which mistake I am doing. In addition, I have tried thisproject on my emulator in Android Studio and my phone in order to understand where I am doing something wrong but even with that project no file is written neither on the phone or on the emulator.
我真的无法理解我在做什么错误。此外,我已经在 Android Studio 和手机中的模拟器上尝试了这个项目,以了解我哪里做错了,但即使使用该项目,也没有在手机或模拟器上写入任何文件。
EDIT: I know that no file is written to my internal storage because I try to read the content of the file, after I have written to it, with this code:
编辑:我知道没有文件写入我的内部存储,因为我尝试读取文件的内容,在我写入文件后,使用以下代码:
public void ReadBtn(View v) {
//reading text from file
try {
FileInputStream fileIn=openFileInput("myFile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
textmsg.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
Nothing is shown at all.
什么都没有显示。
采纳答案by Sandeep dhiman
Use below code to write a file to internal storage
使用以下代码将文件写入内部存储
EDIT:added e.printStackTrace();
to catch block as a good practice and permissions reminders
编辑:添加e.printStackTrace();
到 catch 块作为一种良好的做法和权限提醒
public void writeFileOnInternalStorage(Context mcoContext,String sFileName, String sBody){
File file = new File(mcoContext.getFilesDir(),"mydir");
if(!file.exists()){
file.mkdir();
}
try{
File gpxfile = new File(file, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
}catch (Exception e){
e.printStackTrace();
}
}
And don't forget to add external storage writing AND reading permissions in the manifest:
并且不要忘记在清单中添加外部存储写入和读取权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
After Android 6.0 WRITE_EXTERNAL_STORAGE permission must request in run time
Android 6.0 后 WRITE_EXTERNAL_STORAGE 权限必须在运行时请求
requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE,READ_EXTERNAL_STORAGE}, 1);
and then can handle the result of permission request in onRequestPermissionsResult() method inside activity called from it
然后可以在从它调用的活动中的 onRequestPermissionsResult() 方法中处理权限请求的结果
回答by Kuffs
Have you requested permission to write to external storage?
您是否已请求写入外部存储的权限?
https://developer.android.com/training/basics/data-storage/files.html#GetWritePermission
https://developer.android.com/training/basics/data-storage/files.html#GetWritePermission
Perhaps your try\catch block is swallowing an exception that could be telling you what the problem is.
也许您的 try\catch 块正在吞下一个可能会告诉您问题所在的异常。
Also, you do not appear to be setting the path to save to.
此外,您似乎没有设置保存路径。
e.g: Android how to use Environment.getExternalStorageDirectory()
回答by CommonsWare
no file is written neither on the phone or on the emulator.
没有文件写入手机或模拟器上。
Yes, there is. It is written to what the Android SDK refers to as internal storage. This is notwhat you as a userconsider to be "internal storage", and you as a user cannot see what is in internal storage on a device (unless it is rooted).
就在这里。它被写入 Android SDK 所指的内部存储。这不是您作为用户所认为的“内部存储”,并且您作为用户无法看到设备上的内部存储中的内容(除非它是 root 的)。
If you want to write a file to where users can see it, use external storage.
如果要将文件写入用户可以看到的位置,请使用外部存储。
This sort of basic Android development topic is covered in any decent book on Android app development.
这种基本的 Android 开发主题在任何有关 Android 应用程序开发的体面书籍中都有介绍。
回答by Faxriddin Abdullayev
Save to Internal storage
保存到内部存储
data="my Info to save";
try {
FileOutputStream fOut = openFileOutput(file,MODE_WORLD_READABLE);
fOut.write(data.getBytes());
fOut.close();
Toast.makeText(getBaseContext(), "file saved", Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Read from Internal storage
从内部存储读取
try {
FileInputStream fin = openFileInput(file);
int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}
tv.setText(temp);
Toast.makeText(getBaseContext(), "file read", Toast.LENGTH_SHORT).show();
}
catch(Exception e){
}
回答by Sameh Yassin
To view files on a device, you can log the file location >provided by methods such as File.getAbsolutePath(), and >then browse the device files with Android Studio's Device >File Explorer.
要查看设备上的文件,您可以记录文件位置>由File.getAbsolutePath() 等方法提供,然后>然后使用Android Studio 的设备>文件资源管理器浏览设备文件。
I had a similar problem, the file was written but I never saw it. I used the Device file explorer and it was there waiting for me.
我遇到了类似的问题,文件已写入,但我从未看到过。我使用了设备文件浏览器,它就在那里等着我。
String filename = "filename.jpg";
File dir = context.getFilesDir();
File file = new File(dir, filename);
try {
Log.d(TAG, "The file path = "+file.getAbsolutePath());
file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
return true;