【问题标题】:Java Android Property fileJava Android 属性文件
【发布时间】:2014-08-26 19:28:12
【问题描述】:

我正在尝试在 Android 应用程序中加载保存在我的属性文件中的一些数据。

我已将我的属性文件放在 src 文件夹下。每次我尝试从我的文件中加载数据时,它总是告诉我 FileNotFoundException open failed ENOENT (No such file or directory)。

我的代码如下:

这段代码是保存文件(新建)

      File file = new File("src/com/example/testphonegap/SilverAngel.properties");
      FileOutputStream fileOut = new FileOutputStream(file);
      properties.store(fileOut, "Properties");
      fileOut.close();

这段代码是用来加载数据的

    properties = new Properties();
    InputStream is = null;

     // First try loading from the current directory
    try {
        File f = new File("src/com/example/testphonegap/SilverAngel.properties");
        is = new FileInputStream(f);

        // Try loading properties from the file (if found)
        properties.load(is);

        GetPersonaliseSettings();
        GetUserSettings();
        GetFavSettings();
    }
    catch ( Exception e ) { 
        is = null; 
    }

你能告诉我我做错了什么吗?是文件的保存位置还是我的代码中缺少某些内容?

【问题讨论】:

  • 您是否尝试将目录更改为外部位置,例如外部存储器中的新文件夹
  • 不。请问我该怎么做
  • 文件 f = new File(getApplicationContext().getFilesDir()+"/YourFolderName");
  • 将该文件放在 projectDirectory/res/raw 中,而不是 src。

标签: java android properties filenotfoundexception


【解决方案1】:

这是一个 Android 应用程序,因此文件存储在 Android 设备上,而不是您的计算机上。 如果要将文件保存在 SD 卡上,可以编写以下内容:

String root = Environment.getExternalStorageDirectory().toString();
File dir = new File(root + "/subfolderForYourApp");
dir.mkdirs();

这将为您的应用程序在 SD 卡上创建一个子文件夹。 在此目录中创建一个新文件:

File file = new File(dir, "SilverAngel.properties");
FileOutputStream fileOut = new FileOutputStream(file);
properties.store(fileOut, "Properties");
fileOut.close();

不要忘记在清单中添加权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

【讨论】:

  • 感谢您的帮助。赞赏
【解决方案2】:

试试这个

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("com/example/testphonegap/SilverAngel.properties");
properties.load(inputStream);

确保不要在属性文件名前添加“src”。

【讨论】:

    【解决方案3】:

    将它放在 assets 文件夹中并从那里加载它。

    AssetManager assetManager = context.getAssets();
    InputStream inputStream = assetManager.open("SilverAngel.properties");
    properties.load(inputStream);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-04
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-10
      • 1970-01-01
      相关资源
      最近更新 更多