我已使用此代码在手机的外部存储中创建文件。请注意,我已在我的清单文件中设置了读取和写入权限。
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
Date now = new Date();
String fileName = formatter.format(now) + ".txt"; //like 20170602.txt
File directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
File file = new File(directory, fileName);
String bodyOfFile = "Body of file!";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(bodyOfFile.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
我的LogCat
显示如下。我在该特定位置看不到文件20170602.txt
。在我的Download
文件夹中,没有任何具有该名称的文件。有谁能告诉我哪里出错了。
D/tag: Directory: /storage/emulated/0/Android/data/com.pc.tab/files/Download
D/tag: File: /storage/emulated/0/Android/data/com.pc.tab/files/Download/20170605.txt
更新:
我正在使用MOTO G4来运行这款应用。我在内部存储上找到了20170602.txt
文件。
File Manager --> `LOCAL` tab ( Upper right ) --> Internal Storage --> Android --> data --> com.pc.tab --> files --> Download --> 20170602.txt
答案 0 :(得分:1)
将目录和文件本身分开是很重要的
File directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
File file = new File(directory, fileName);
在您的代码中,您在要写入的文件上调用mkdirs,这是一个错误,因为mkdirs使您的文件成为一个目录。您应该只为目录调用mkdirs,以便在它不存在时创建它,并且在为此文件创建新的FileOutputStream对象时将自动创建该文件。
您的代码应如下所示:
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
Date now = new Date();
String fileName = formatter.format(now) + ".txt"; //like 20170602.txt
File directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
File file = new File(directory, fileName);
String bodyOfFile = "Body of file!";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(bodyOfFile.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}