【发布时间】:2011-04-23 20:07:45
【问题描述】:
我尝试在我的文件夹中保存一个 txt 文件,在内部存储中,但我每次都面临同样的问题:
“未找到源”
我以不同的方式编写代码,如下所示,但在所有方面我都有同样的问题。
值得一说,我什至加了
<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();
}
【问题讨论】:
-
在编写问题时选择代码并按 ctrl+k,这将自动缩进并着色您的代码,因此更具可读性。没有人愿意阅读未缩进和未着色的代码。
标签: android