【问题标题】:Creating and writing a file android创建和写入文件android
【发布时间】:2014-10-07 11:30:44
【问题描述】:

我正在尝试写入我的 android 应用程序中的文件。

我认为它不会创建文件。

  1. 代码要更正吗?

  2. 如果是,我如何在手机上找到该文件?隐藏了吗?

代码位于 Activity 片段中

        String FILENAME = "alarmStatus";
        FileOutputStream fos;
        try {
            fos = getActivity().openFileOutput(FILENAME, MODE_PRIVATE);
            fos.write("Hello".getBytes());
            fos.close();


        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

【问题讨论】:

  • 您遇到错误了吗?你有没有通过代码?文件怎么说?在这里提出问题应该是您的第五或第六步,而不是您的第二步(在编写和执行代码之后)。
  • 嗨,戴夫,感谢您的回复。起初,当我尝试引入一个目录来写入文件时,我遇到了“只读文件系统”错误。我已经阅读了开发者文档,并且我试图按照他们的示例进行操作。 developer.android.com/guide/topics/data/…
  • 08-14 00:01:20.847:W/System.err(21797):java.io.IOException:打开失败:EROFS(只读文件系统)
  • 问题是我不知道文件在哪里,我使用文件管理器应用程序尝试找到它,但我看不到它。我也不知道如何在创建时更改文件权限。
  • @MobileDeveloper :Fragment 类没有 openFileOutput 方法。该方法仅适用于扩展 ContextWrapper 或 Context 的类。

标签: android io internal-storage


【解决方案1】:

我想我找到了一个解决方案,有点啰嗦但它确实有效,请戳它:)

      File file = new File(getActivity().getFilesDir() +"alarmStatus.txt");
        OutputStream out = null;

        try {
            out = new BufferedOutputStream(new FileOutputStream(file));
            out.write("Hello".getBytes());
           out.close();

        }catch(Exception e){

        }

        BufferedReader in =null;

        try{
            FileInputStream fis = new FileInputStream(file);
            in = new BufferedReader(new InputStreamReader(fis));
            System.out.println("File Output is "+in.readLine());


        }catch(Exception e){

        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    相关资源
    最近更新 更多