自己想写个沙雕app,使用文件存储需要判断文件是否存在,但是一直报错,就改各种东西。最后想去看看Deviced File Explorer 文件管理器,结果发现问题出在居然没法通过file.exists()来判断指定的某个文件存在。查看打印,file.exists()返回值居然始终是false,实际上此文件是存在的,存在的!
总结:
exists()方法内的file必须是绝对路径才行,相对路径不行。
String AbsolutePath=getDataDir().getAbsolutePath();
//这个路径是内部路径,根据个人需求自己换,但总之是绝对路径
String filename="egoist.txt";
File f=new File(AbsolutePath+filename);
Boolean bool=f.exists();
另外,最好自己写一个方法判断是否存在:
//判断文件是否存在
public boolean fileIsExists(String filename)
{
try
{
String AbsolutePath=getFilesDir().getAbsolutePath();
File f=new File(AbsolutePath+"/"+filename);
if(!f.exists())
{
return false;
}
}
catch (Exception e)
{
return false;
}
return true;
}
探究:
public class MainActivity extends AppCompatActivity {
private Button button;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button= this.<Button>findViewById(R.id.button);
textView= this.<TextView>findViewById(R.id.tv);
}
public void cc(View v) throws IOException {
String fileName="data.txt";
String content="helloword";
FileOutputStream fos;
try
{
fos=openFileOutput(fileName,MODE_PRIVATE);
//还有MODE_APPEND追加
fos.write(content.getBytes());
//转化成byte[]的形式写入
fos.close();
}catch (Exception e) {
e.printStackTrace();
}
File test=new File(fileName);
if(!test.exists())
{
textView.setText("不写路径居然不对");
}
else
{
textView.setText("你也是个坑");
}
}
}
PS:搜到android:sharedUserId=”android.uid.system”高级权限,这是什么鬼┏┛墓┗┓...(((m -__-)m