是否可以从内部存储(Android)读取文件?

Tir*_*tha 0 android android-intent

我想在内部存储中保存文件.下一步是我要读取文件.使用FileOutputStream在内部存储中创建文件,但读取文件时出现问题.

是否可以访问内部存储来读取文件?

Sha*_*wal 7

是的,您可以从内部存储中读取文件.

对于写文件,你可以使用它

String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
Run Code Online (Sandbox Code Playgroud)

阅读文件使用如下:

要从内部存储中读取文件:

调用openFileInput()并传递要读取的文件的名称.这会返回一个FileInputStream.用文件读取文件中的字节read().然后关闭流close().

码:

StringBuilder sb = new StringBuilder();
try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        is.close();
    } catch(OutOfMemoryError om) {
        om.printStackTrace();
    } catch(Exception ex) {
        ex.printStackTrace();
    }
    String result = sb.toString();
Run Code Online (Sandbox Code Playgroud)

请参阅此链接


Tir*_*tha 6

可以从内部存储器写入和读取文本文件.在内部存储的情况下,不需要直接创建文件.使用FileOutputStream写入文件.FileOutputStream 将自动在内部存储中创建文件.无需提供任何路径,您只需提供文件名即可.现在阅读文件使用FileInputStream.它将自动从内部存储中读取文件.下面我提供了读写文件的代码.

编写文件的代码

String FILENAME ="textFile.txt";
String strMsgToSave = "VIVEKANAND";
FileOutputStream fos;
try
{
    fos = context.openFileOutput( FILENAME, Context.MODE_PRIVATE );
    try
    {
        fos.write( strMsgToSave.getBytes() );
        fos.close();

    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

}
catch (FileNotFoundException e)
{
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

}

代码阅读文件

int ch;
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis;
try {
    fis = context.openFileInput( FILENAME );
    try {
        while( (ch = fis.read()) != -1)
            fileContent.append((char)ch);
    } catch (IOException e) {
        e.printStackTrace();
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

String data = new String(fileContent);
Run Code Online (Sandbox Code Playgroud)