【问题标题】:Using InputStream to read file from internal storage使用 InputStream 从内部存储中读取文件
【发布时间】:2013-04-28 20:42:02
【问题描述】:

我已经搜索了几天,我发现的只是使用 bufferedReader 从内部存储上的文件中读取。不能使用 InputStream 从内部存储中读取文件吗?

private void dailyInput()
{    
    InputStream in;
    in = this.getAsset().open("file.txt");
    Scanner input = new Scanner(new InputStreamReader(in));
    in.close();
}

我现在将它与input.next() 一起使用,以在我的文件中搜索我需要的数据。一切正常,但我想将新文件保存到内部存储并从中读取,而无需将所有内容更改为 bufferedReader。这是可能的还是我需要硬着头皮改变一切?仅供参考,我不需要写,只需要阅读。

【问题讨论】:

    标签: android inputstream


    【解决方案1】:

    写入文件。

    String FILENAME = "file.txt";
    String string = "hello world!";
    
    FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
    fos.write(string.getBytes());
    fos.close();
    

    阅读

    void OpenFileDialog(String file) {
    
        //Read file in Internal Storage
        FileInputStream fis;
        String content = "";
        try {
            fis = openFileInput(file);
            byte[] input = new byte[fis.available()];
            while (fis.read(input) != -1) {
            }
            content += new String(input);
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
    

    content 将包含您的文件数据。

    【讨论】:

    • 要访问设备内部存储上的文件,是否需要将FILENAME字符串设置为设备上file.txt的路径?此外,fis.read();只能读入int?
    • fis.read() 只能读入 int。此外,使用此方法时出现运行时错误(可能路径错误)。我正在使用扫描仪在文档中搜索我需要的数据。这允许我一次读取一个字符串。不能将扫描仪与内部存储中的文件一起使用吗?
    • k.我正在编辑我的答案看到它
    • 谢谢,这似乎让我走上了正轨。还有一个问题,如何指定文件路径?
    • 使用 available() 分配内存是不正确的,如文档developer.android.com/reference/java/io/… 中所述“请注意,虽然 InputStream 的某些实现将返回流中的字节总数,但许多不会。它是永远不要正确使用此方法的返回值来分配一个缓冲区,该缓冲区旨在保存此流中的所有数据。"
    【解决方案2】:

    当您遇到从内部存储的子文件夹中读取文件的情况时,您可以尝试以下代码。有时您可能会遇到 openFileInput 问题,因为您尝试传递上下文。 这是功能。

        public String getDataFromFile(File file){  
         StringBuilder data= new StringBuilder();  
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String singleLine;
            while ((singleLine= br.readLine()) != null) {
                data.append(singleLine);
                data.append('\n');
            }
            br.close();
            return data.toString();
        }
        catch (IOException e) {
            return ""+e;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      • 2017-03-21
      • 2013-06-06
      • 1970-01-01
      • 1970-01-01
      • 2013-01-23
      相关资源
      最近更新 更多