【问题标题】:How can I write a file with an android app?如何使用 android 应用程序编写文件?
【发布时间】:2013-03-20 18:18:12
【问题描述】:

我编写了一个加密应用程序,它将为 RSA 生成一个公钥私钥对。私钥需要保存在设备上。在使用普通 java 应用程序进行测试时,生成了密钥,然后使用以下内容保存到文件中:

public static void saveToFile(String fileName,BigInteger mod, BigInteger exp) throws IOException
   {
    ObjectOutputStream oout = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)));
        try
        {
                oout.writeObject(mod);
                oout.writeObject(exp);
        }

        catch (Exception e)
        {
                throw new IOException("Unexpected error", e);
        }

        finally
        {
                oout.close();
        }
}

密钥文件将出现在项目目录中。但是,对于 android 应用程序,这不会发生。如何使用 android 应用编写文件?

谢谢!

【问题讨论】:

标签: android file


【解决方案1】:

密钥文件将出现在项目目录中。但是,对于 android 应用程序,这不会发生。如何使用 android 应用编写文件?

在 Android 中,您的应用程序只有两个主要的地方可以写入文件:私有内部存储目录和外部存储卷。您需要做的不仅仅是提供文件名,还必须提供包含这些位置的完整路径。

//Internal storage location using your filename parameter
File file = new File(context.getFilesDir(), filename);

//External storage location using your filename parameter
File file = new File(Environment.getExternalStorage(), filename);

不同之处在于内部存储只能由您的应用访问;如果您通过 USB 连接和安装存储,则可以从任何地方读取/写入外部存储,包括您的 PC。

然后您可以将适当的文件包装在现有代码的FileOutputStream 中。

【讨论】:

  • 感谢您的帮助。也许我完全错过了一些东西,但你从哪里得到“背景”?事实上,netbeans 告诉我“找不到符号:变量上下文”。对不起,如果这是一个愚蠢的问题。这是我尝试构建的第一个应用程序。
  • 这只是为了表明getFilesDir()Context 上的一个方法,因此您可以在您拥有的任何Context 对象上调用它。 ActivityService 等系统组件都继承自 Context
  • 我想我还是不明白。我没有任何上下文对象。其实它是一个抽象类,不能实例化。
  • 如果您在Activity 内运行此代码,则可以直接使用getFilesDir()。如果它在另一个类中,则需要将 Context 传递给方法(例如,如果它是 Activity 调用的,则将 this 传递给方法)。否则,您需要使用不需要的外部存储版本。
  • 啊!是的,我将方法的核心直接移到 MainActivity(它扩展了 Activity)中,然后 getFilesDir() 自行工作。现在,我仍然看不到我正在尝试创建的文件。我想知道我是否能够做到?它们会出现在项目目录中,还是只存在于模拟器中的某个阴间?
【解决方案2】:

首先从你调用的主类作为方法:

Boolean writfile;
writfile =savTextFileInternal(this.getApplicationContext(),"Maa","Ambika");
Toast.makeText(this, "File write:"+writfile, Toast.LENGTH_LONG).show();

创建一个这样的方法:

public boolean savTextFileInternal(Context context,String sFileName, String sBody)
{
    try
    {
        File root = new File(context.getFilesDir(),"myfolder");

        if (!root.exists()) {
            root.mkdirs();
        }

        File gpxfile = new File(root, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
        return  true;  
    }
    catch(IOException e)
    {
        e.printStackTrace();
        return false;
    }
}

【讨论】: