这是我正在运行的代码:
File root = android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File dir = new File(root.getAbsolutePath());
dir.mkdirs();
File file = new File(dir, "myData.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Hi , How are you");
pw.println("Hello");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
android.util.Log
.i("tag",
"******* File not found. Did you add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
代码执行没有问题,如果我运行这些测试,所有显示该文件存在于文件系统上:
File testFile = new File(dir, "myData.txt");
Boolean exists = testFile.exists();//true
Boolean hidden = testFile.isHidden();//false
String[] files = dir.list();//list contains the file
但我无法在文件资源管理器或根浏览器或终端仿真器中看到该文件。 AND dir.list()
查询的文件列表与我在/mnt/sdcard/Downloads
的根浏览器中看到的文件列表不同。我尝试使用myData.txt
在终端模拟器中搜索文件find / -name *myData*
但没有结果。
我在root s4上运行代码,AndroidManifest包含WRITE_EXTERNAL_STORAGE权限。
为什么会发生这种情况?如何让用户在创建文件后看到该文件?
答案 0 :(得分:3)
也许您没有使用MediaScannerConnection
索引它们,或者您的计算机可能会将MTP连接的结果缓存到设备。
答案 1 :(得分:1)
我的活动:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File root = android.os.Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File dir = new File(root.getAbsolutePath());
dir.mkdirs();
File file = new File(dir, "myData.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Hi , How are you");
pw.println("Hello");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
android.util.Log
.i("tag",
"******* File not found. Did you add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
<强>清单:强>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.Test.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<强>输出:强>