我尝试将文件txt保存到公共外部存储
文件清单
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hikilam.publicprivateexternalstorage">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
file xml
<RelativeLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.hikilam.publicprivateexternalstorage.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Username"
android:id="@+id/textView"
android:layout_marginTop="126dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/user"
android:width="200dp"
android:layout_alignBottom="@+id/textView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Public"
android:id="@+id/button"
android:onClick="publicStorage"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
保存功能:
public void publicStorage(View view) {
String data = username.getText().toString();
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File file1 = new File(file, "file.txt");
FileOutputStream fileOutputStream=null;
try {
fileOutputStream=new FileOutputStream(file1);
fileOutputStream.write(data.getBytes());
Toast.makeText(this,"Stored Succeful"+file1.getAbsolutePath(),Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
错误代码
02-29 20:53:19.511 4696-4696/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hikilam.publicprivateexternalstorage, PID: 4696
java.lang.IllegalStateException: Could not execute method for android:onClick