我尝试在我的文件夹中保存一个 txt 文件,在内部存储中,但我每次都面临同样的问题:
"Source Not Found"
我以不同的方式编写代码,如下所示,但在所有方面我都有同样的问题。
值得一说,我什至加了
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
在内部存储不需要的 Manifest.xml 中。
不用说我将文件保存在 /data/data/package/files 路径中没有任何问题,但是当我将文件夹添加到文件的根目录时/data/data/package/files/myforlder/myfile.txt 我面临“找不到源”问题。
你能指出我解决这个问题的正确方向吗?
第二个问题是,用于将文件保存在外部存储中的外部文件夹中。
(例如:sdCard或USB存储)场景不同还是相同?
第一种方式:
OutputStreamWriter out;
try {
File path=new File(getFilesDir(),"myfolder");
File mypath=new File(path,"myfile.txt");
if (!mypath.exists()) {
out = new OutputStreamWriter(openFileOutput( mypath.getAbsolutePath() , MODE_PRIVATE));
out.write("test");
out.close();
}
}
第二种方式:
OutputStreamWriter out;
try {
ContextWrapper cw = new ContextWrapper(this);
File path = cw.getDir("myfolder", Context.MODE_PRIVATE);
if (!path.exists()) {
path.createNewFile();
path.mkdir();
}
File mypath=new File(path,"myfile.txt");
if (!mypath.exists()) {
out = new OutputStreamWriter(openFileOutput( mypath.getAbsolutePath() , MODE_PRIVATE));
out.write("test");
out.close();
}
}
第三种方式:
File path=getFilesDir();
String mypath=path.toString() + "/myfolder";
OutputStreamWriter out;
try {
File f = new File(mypath , "/myfile.txt" );
out = new OutputStreamWriter(openFileOutput(f.getPath(), MODE_PRIVATE));
out.write("test");
out.close();
}
第四条路:
File path=getFilesDir();
OutputStreamWriter out;
try {
File f = new File(path.getPath() + "/myfolder/myfile.txt" );
out = new OutputStreamWriter(openFileOutput(f.getPath(), MODE_PRIVATE));
out.write("test");
out.close();
}
第五种方式:
File path=getFilesDir();
OutputStreamWriter out;
try {
File f = new File(path.getCanonicalPath() + "/myfile.txt");
out = new OutputStreamWriter(openFileOutput( f.getPath(), MODE_PRIVATE));
out.write("test");
out.close();
}
最佳答案
First Way:
您没有创建目录。此外,您将绝对路径传递给 openFileOutput()
,这是错误的。
Second way:
您创建了一个具有所需名称的空文件,这阻止了您创建目录。此外,您将绝对路径传递给 openFileOutput()
,这是错误的。
Third way:
您没有创建目录。此外,您将绝对路径传递给 openFileOutput()
,这是错误的。
Fourth Way:
您没有创建目录。此外,您将绝对路径传递给 openFileOutput()
,这是错误的。
Fifth way:
您没有创建目录。此外,您将绝对路径传递给 openFileOutput()
,这是错误的。
正确方法:
- 为您想要的目录创建一个
File
(例如,File path=new File(getFilesDir(),"myfolder");
) - 在该
File
上调用mkdirs()
以创建目录(如果该目录不存在) - 为输出文件创建一个
File
(例如,File mypath=new File(path,"myfile.txt");
) - 使用 standard Java I/O写入该
File
(例如,使用new BufferedWriter(new FileWriter(mypath))
)
关于android - 将内部文件保存在我自己的 Android 内部文件夹中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5766609/