【问题标题】:Create a file locally on android(not on SD card)在 android 本地创建文件(不在 SD 卡上)
【发布时间】:2023-03-13 07:14:01
【问题描述】:

我遇到了一个问题,我试图在 android 模拟器上本地创建一个文件,但是当我测试它时文件存在,它不存在。我无权访问物理 android 设备,所以我使用模拟器。 请注意,我不想将文件保存在 SD 卡上。我对android的文件结构不是很熟悉,如果我的代码没有意义,请原谅我。 这是我目前正在使用的代码,它不起作用:(

EditText editText = (EditText) findViewById(R.id.editTextName);
        String  sName = editText.getText().toString();

        editText = (EditText) findViewById(R.id.editTextEmail);
        String  sEmail = editText.getText().toString();

        editText = (EditText) findViewById(R.id.editTextPostal);
        String  sPostal = editText.getText().toString();

File file = new File("/storage/new/test.txt");
        FileOutputStream fos;
        byte[] data = new String("Name: " + sName + " Subject: " + sEmail + " Question: " + sPostal ).getBytes();

        OutputStream myOutput;
            try {
            myOutput = new BufferedOutputStream(new FileOutputStream(file,true));
            myOutput.write(data);
            myOutput.flush();
            myOutput.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        if(file.exists())
        {
            finish();
        }

有没有人在 android 开发领域有足够的经验给我提供一些示例代码或指出正确的方向,以便我可以让这个坏男孩工作? 编辑:当我说它不起作用时,我的意思是永远不会创建文件。

【问题讨论】:

    标签: android eclipse android-emulator io


    【解决方案1】:

    如果您不熟悉 Android 中的文件存储,我建议您阅读 this piece of documentation 以开始使用 - 它应该通过示例回答您的问题。

    【讨论】:

    • 感谢您的回复。 “使用内部存储”下的代码似乎可行。这是否允许我使用文件名(在本例中为“hello_file”)来引用文件,以便我可以在稍后阶段对文件执行某些操作?
    • 如果您的意思是访问该文件,就好像它在您的项目资源中一样,不。您应该始终通过其路径访问它。
    猜你喜欢
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    • 2016-04-18
    • 2020-03-05
    • 2018-05-18
    • 2020-04-10
    • 2013-07-24
    • 1970-01-01
    相关资源
    最近更新 更多