0

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

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

4

4 回答 4

7

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

写文件你可以用这个

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

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

要读取文件,请使用以下命令:

从内部存储读取文件:

调用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();

参考这个链接

于 2012-06-02T06:35:09.143 回答
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();
}

}

读取文件的代码

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);
于 2012-06-12T07:22:55.987 回答
1

该线程似乎正是您正在寻找的读/写文件到内部私人存储

有一些很好的提示。

于 2012-06-02T06:36:11.313 回答
0

绝对没错,

阅读此http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

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

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());

fos.close();
于 2012-06-02T06:43:35.577 回答