android - 如何使用 Android 应用程序编写文件?

标签 android file

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

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();
        }
}

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

谢谢!

最佳答案

The key file would appear in the project directory. However, with the android app, this does not happen. How can I write a file with an android app?

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

//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 中。

关于android - 如何使用 Android 应用程序编写文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15713546/

相关文章:

android - 在 android 中过滤 ListView 时检查了错误的项目

android - Sencha Touch 2.3 与 Cordova 3.5 的启动时间很长

android SQLite - 管理具有多个用户的单个数据库

r - list.files考虑到R中的文件大小?

c - 为什么“while(!feof(file))”总是错误的?

java - Android中Thread.currentThread().getId()和Process.myTid()的区别

升级外接主板的安卓应用

java - 有没有什么方法可以使用java api在文本文件中定位带有行号的行?

python - 从文件中读取行的生成器

从数据文件读取矩阵,然后计算它们的乘积,然后将结果矩阵打印到数据文件的代码