我是android的新手。我创建了一个应用程序,用于从内部和外部存储创建和读取文本文件。在外部和内部存储中成功完成文本文件创建。从外部存储读取文件也有效但在从内部存储读取文件时遇到问题并且获取错误“获取文件内容时出错:FileName.txt”
请参阅以下代码:
// MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
private String filename = "StorageFile.txt";
private String filepath = "FileStorage";
File myInternalFile;
File myExternalFile;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ContextWrapper contextWrapper = new ContextWrapper(
getApplicationContext());
File directory = contextWrapper.getDir(filepath, Context. MODE_WORLD_WRITEABLE);
myInternalFile = new File(directory, filename);
Button saveToInternalStorage = (Button) findViewById(R.id.InternalStorageSave);
saveToInternalStorage.setOnClickListener(this);
Button readFromInternalStorage = (Button) findViewById(R.id.InternalStorageGet);
readFromInternalStorage.setOnClickListener(this);
Button saveToExternalStorage = (Button) findViewById(R.id.ExternalStorageSave);
saveToExternalStorage.setOnClickListener(this);
Button readFromExternalStorage = (Button) findViewById(R.id.ExternalStorageGet);
readFromExternalStorage.setOnClickListener(this);
// check if external storage is available and not read only
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
saveToExternalStorage.setEnabled(false);
} else {
myExternalFile = new File(getExternalFilesDir(filepath), filename);
}
}
public void onClick(View v) {
EditText myInputText = (EditText) findViewById(R.id.InputText);
TextView responseText = (TextView) findViewById(R.id.responseText);
String myData = "";
switch (v.getId()) {
case R.id.InternalStorageSave:
try {
FileOutputStream fos = openFileOutput(filename,
Context.MODE_PRIVATE);
fos.write(myInputText.getText().toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
myInputText.setText("");
responseText.setText("Saved to Internal Storage.(StorageFile.txt)");
break;
case R.id.InternalStorageGet:
try {
FileInputStream fis = openFileInput(filename);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(
new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
myInputText.setText(myData);
responseText
.setText("Data retrieved from Internal Storage.(StorageFile.txt)");
openFile(myInternalFile);
break;
case R.id.ExternalStorageSave:
try {
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(myInputText.getText().toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
myInputText.setText("");
responseText.setText("Saved to External Storage.(StorageFile.txt)");
break;
case R.id.ExternalStorageGet:
try {
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(
new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
myInputText.setText(myData);
responseText
.setText("Data retrieved from Internal Storage.(StorageFile.txt)");
openFile(myExternalFile);
break;
}
}
private void openFile(File file) {
final Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
final MimeTypeMap mime = MimeTypeMap.getSingleton();
final String ext = file.getName().substring(
file.getName().indexOf(".") + 1);
final String type = mime.getMimeTypeFromExtension(ext);
intent.setDataAndType(Uri.fromFile(file), type);
startActivity(intent);
}
private static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
private static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
// activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Storage Demo" />
<EditText
android:id="@+id/InputText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="top|left"
android:inputType="textMultiLine"
android:lines="5"
android:minLines="2"
android:text="Internal and External Storage" >
<requestFocus />
</EditText>
<Button
android:id="@+id/InternalStorageSave"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Internal Storage(Save)" />
<Button
android:id="@+id/InternalStorageGet"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Internal Storage(Display)" />
<Button
android:id="@+id/ExternalStorageSave"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="External Storage(Save)" />
<Button
android:id="@+id/ExternalStorageGet"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="External Storage(Displays)" />
<TextView
android:id="@+id/responseText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
此外,我在下面添加了读取和写入文件到外部存储的权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
定位输出:
12-27 02:20:22.795: E/StrictMode(944): file:// Uri exposed through Intent.getData()
12-27 02:20:22.795: E/StrictMode(944): java.lang.Throwable:
file:// Uri exposed through Intent.getData()
12-27 02:20:22.795: E/StrictMode(944): at
android.os.StrictMode.onFileUriExposed(StrictMode.java:1597)
12-27 02:20:22.795: E/StrictMode(944): at
android.net.Uri.checkFileUriExposed(Uri.java:2338)
12-27 02:20:22.795: E/StrictMode(944): at
android.content.Intent.prepareToLeaveProcess(Intent.java:7194)
12-27 02:20:22.795: E/StrictMode(944): at
android.app.Instrumentation.execStartActivity(Instrumentation.java:1418)
12-27 02:20:22.795: E/StrictMode(944): at
android.app.Activity.startActivityForResult(Activity.java:3423)
12-27 02:20:22.795: E/StrictMode(944): at android.app.Activity.startActivityForResult
(Activity.java:3384)
12-27 02:20:22.795: E/StrictMode(944): at android.app.Activity.startActivity
(Activity.java:3626)
12-27 02:20:22.795: E/StrictMode(944):
at android.app.Activity.startActivity(Activity.java:3594)
12-27 02:20:22.795: E/StrictMode(944): at
com.android.internal.app.ResolverActivity.onIntentSelected(ResolverActivity.java:407)
12-27 02:20:22.795: E/StrictMode(944): at
com.android.internal.app.ResolverActivity.startSelected(ResolverActivity.java:299)
12-27 02:20:22.795: E/StrictMode(944): at
com.android.internal.app.ResolverActivity.onButtonClick(ResolverActivity.java:289)
12-27 02:20:22.795: E/StrictMode(944): at
java.lang.reflect.Method.invokeNative(Native Method)
12-27 02:20:22.795: E/StrictMode(944): at
java.lang.reflect.Method.invoke(Method.java:515)
12-27 02:20:22.795: E/StrictMode(944): at android.view.View$1.onClick(View.java:3809)
12-27 02:20:22.795: E/StrictMode(944):at android.view.View.performClick(View.java:4424)
12-27 02:20:22.795: E/StrictMode(944):at
android.view.View$PerformClick.run(View.java:18383)
12-27 02:20:22.795: E/StrictMode(944): at android.os.Handler.handleCallback
(Handler.java:733)
12-27 02:20:22.795: E/StrictMode(944): at android.os.Handler.dispatchMessage
(Handler.java:95)
12-27 02:20:22.795: E/StrictMode(944): at android.os.Looper.loop(Looper.java:137)
12-27 02:20:22.795: E/StrictMode(944): at android.app.ActivityThread.main
(ActivityThread.java:4998)
12-27 02:20:22.795: E/StrictMode(944): at java.lang.reflect.Method.invokeNative
(Native Method)
12-27 02:20:22.795: E/StrictMode(944): at
java.lang.reflect.Method.invoke(Method.java:515)
12-27 02:20:22.795: E/StrictMode(944): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
12-27 02:20:22.795: E/StrictMode(944): at com.android.internal.os.ZygoteInit.main
(ZygoteInit.java:593)
12-27 02:20:22.795: E/StrictMode(944): at dalvik.system.NativeStart.main
(Native Method)
12-27 02:20:22.815: I/ActivityManager(371): START u0
{act=android.intent.action.VIEW dat=file:///data/data/com.example.external/
app_FileStorage/StorageFile.txt typ=text/plain \
flg=0x3000000 cmp=com.android.htmlviewer/.HTMLViewerActivity} from pid 944
12-27 02:20:23.015: D/gralloc(49): Registering a buffer in the process that
created it. This may cause memory ordering problems.
12-27 02:20:23.015: E/libEGL(49): called unimplemented OpenGL ES API
12-27 02:20:23.015: E/libEGL(49): called unimplemented OpenGL ES API
12-27 02:20:23.015: E/libEGL(49): called unimplemented OpenGL ES API
12-27 02:20:23.025: E/libEGL(49): called unimplemented OpenGL ES API
12-27 02:20:23.025: E/SurfaceFlinger(49): glCheckFramebufferStatusOES error -480946759
12-27 02:20:23.025: E/SurfaceFlinger(49): got GL_FRAMEBUFFER_COMPLETE_OES
error while taking screenshot
12-27 02:20:23.025: E/libEGL(49): called unimplemented OpenGL ES API
12-27 02:20:23.025: E/libEGL(49): called unimplemented OpenGL ES API
12-27 02:20:23.025: W/WindowManager(371): Screenshot failure taking
screenshot for (328x546) to layer 21015
12-27 02:20:23.805: D/dalvikvm(1133): GC_FOR_ALLOC freed 49K, 2% free
6543K/6656K, paused 77ms, total 92ms
12-27 02:20:24.545: W/AwContents(1133): nativeOnDraw failed;
clearing to background color.
12-27 02:20:24.625: I/Choreographer(944): Skipped 153 frames!
The application may be doing too much work on its main thread.
12-27 02:20:25.795: W/AwContents(1133): nativeOnDraw failed;
clearing to background color.
12-27 02:20:25.945: I/ActivityManager(371): Displayed
com.android.htmlviewer/.HTMLViewerActivity: +2s834ms
12-27 02:20:25.945: I/Choreographer(371): Skipped 32 frames! The application may
be doing too much work on its main thread.
12-27 02:20:26.165: E/AndroidProtocolHandler(1133): Unable to open content URL:
content: //com.android.htmlfileprovider/data/data/com.example.external/
app_FileStorage/StorageFile.txt?text/plain
您能告诉我如何从内部存储中读取文件吗?
此致 Shainaz
答案 0 :(得分:0)
尝试这样的事情:
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(
openFileInput("DayTwentyTwoFile")));
String inputString;
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null) {
stringBuffer.append(inputString + "\n");
}
lblTextViewOne.setText(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
答案 1 :(得分:0)
我希望您对数据\数据目录文件的说法是特定于任何应用程序的。因此,如果您希望能够访问任何应用程序的data \ data文件,那么应用程序应该就内容提供者和权限提供权限,如果有任何指定的话。
如果它的内部存储没有您可以阅读的问题,请使用下面的androidmanifest.xml权限编写它
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>