【问题标题】:Reading int value from txt file on SD card android从SD卡android上的txt文件中读取int值
【发布时间】:2010-12-30 02:29:58
【问题描述】:

所以在我制作的这个应用程序中,用户创建了一个项目,当他们保存时,帧数会保存到 SD 卡上的 numberFrames.txt 中。然后我在另一个类中检索文件。唯一的问题是,当我在运行此代码后向屏幕显示 nFrames 时,nFrames = 50。我对 nFrames 所做的唯一初始化是在位于 onCreate() 中的代码正上方归零。

File sdcardLocal =  Environment.getExternalStorageDirectory();
                 File dir = new File (sdcardLocal.getAbsolutePath() + "/Flipbook/"+customizeDialog.getTitle()+"/");
                 dir.mkdirs();
                 File fileNum = new File(dir, "numberFrames.txt");
                 FileWriter myFileWriter = null;
        try {
         myFileWriter = new FileWriter(fileNum);
        } catch (IOException e) {
         e.printStackTrace();
        }
                 BufferedWriter out = new BufferedWriter(myFileWriter); 
                          try {
                           String text = bitmaps.size()+"";
                           out.write(text);
         out.close();
        } catch (IOException e) {
         e.printStackTrace();
        }

我像这样检索文件。我不知道 nFrames 的这个“50”值是从哪里来的,因为周围没有循环,而且我确定保存的特定项目只有 3 帧。这是为什么呢?

FileInputStream is = null;
             BufferedInputStream bis = null;
             try {
                 is = new FileInputStream(new File(mFolderDialog.getPath()+"/numberFrames.txt"));
                 bis = new BufferedInputStream(is);
                 nFrames = bis.read();
             }catch (IOException e) {
     e.printStackTrace();
    }

【问题讨论】:

    标签: android file int sd-card


    【解决方案1】:

    您正在写出一个字符串,然后将第一个字节作为整数读取。 50 是 '2' 字符的 ASCII 码。

    您可以使用 BufferedReader.readLine 将文件的整个第一行作为字符串读取,然后使用 Integer.parseInt 将其转换为整数。

    另外,我会仔细研究一下您的应用程序的工作流程。您没有提供太多信息,但是将具有单个整数值的文件保存到 sdcard 有一定的“气味”:)。您是否考虑过使用数据库,或者将文本文件存储在应用程序的目录中?

    【讨论】:

    • 是的,我走错了方向。我找到了一种获取文件夹中项目数量的方法,并且首先消除了我保存 txt 文件的需要。
    猜你喜欢
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    相关资源
    最近更新 更多