有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android文件不存在(但同时存在!)

我有一个Android程序,它创建一个文件并在if语句中检查它。这样做的目的是能够在应用程序中保存值。这个应用程序就是这样工作的。我在手机上输入了这些值,然后使应用程序崩溃以重置它。这些值保存在文件中。当我再次打开应用程序时,应该跳过让我输入值的屏幕。当我这样做时,应用程序的行为就好像该文件从未存在过一样。调试时,我发现确实创建了该文件。它应该是在内部存储上创建的,但我还添加了外部存储写入权限,以防万一。有人能帮我或给我一个选择吗

File file = new File("user.txt");
    if (file.exists())
    {
        ...
    }

共 (4) 个答案

  1. # 1 楼答案

    试着给它一个完整的路径,不仅仅是文件名,像这样

    File mFile = new File("/sdcard/mysdfile.txt");
    
  2. # 2 楼答案

    资产文件夹在运行时是只读的

    http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

    Tip: If you want to save a static file in your application at compile time, save the file in your project res/raw/ directory. You can open it with openRawResource(), passing the R.raw. resource ID. This method returns an InputStream that you can use to read the file (but you cannot write to the original file).

    看看使用SharedPreferences保存基本数据类型

  3. # 3 楼答案

            File f = new File(); 
    

    它只是在运行时创建一个file的文件实例。您需要使用以下代码来创建文件

            File file = new File("data/data/your package name/test.txt");
            if (!file.exists()) {
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
    
  4. # 4 楼答案

            Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    
                    File direct = new File(Environment.getExternalStorageDirectory() + "/Folder/Filename");
                    if (!direct.exists()) {
                        direct.mkdir(); // directory is created;
                    }
                    if (isSDPresent) {
                        Path = Environment.getExternalStorageDirectory() + "/Folder/Filename";
    
                    } else {
                        Path = getFilesDir() + "/Folder/Filename";
                    }
            File f = new File(Path);
          if(!file.exists()) {
           try {
                            file.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
    }