如何从android中的档案文件中读取文件

时间:2014-01-08 13:21:10

标签: android file

我有一个扩展名为“.dth”的存档文件。在其中我有两个文件 colors.txt stack.txt 。我把它放在手机内存的sdk目录中。现在尝试读取存档和LogCat打印每个文件的内容。我用了代码:

private void readThemeFile()
{
    File myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/myFile.dth");
    FileInputStream is;

    try
    {
        is = new FileInputStream(myFile);
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));

        ZipEntry ze;

        if (zis.getNextEntry() == null) Log.d("Next Entry", "is null");

        while ((ze = zis.getNextEntry()) != null)
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];

            int count;

            while ((count = zis.read(buffer)) != -1)
                baos.write(buffer, 0, count);

            String filename = ze.getName();

            byte[] bytes = baos.toByteArray();

            Log.d("File Name:", filename);
            Log.d("Bytes Length:", bytes.length + "");

            zis.close();
        }
    } 

    catch (FileNotFoundException e) { Log.d("Message:", "File not found."); }

    catch (IOException e) { Log.d("Message:", "IOException occurred."); }
}

然而,在读取stack.txt后,它出现了IO异常:

01-08 19:58:20.238: D/File Name:(1202): stack.txt
01-08 19:58:20.238: D/Bytes Length:(1202): 46
01-08 19:58:20.248: I/keystore(1271): uid: 1000 action: e -> 7 state: 3 -> 3 retry: 4
01-08 19:58:20.248: I/keystore(1271): uid: 1000 action: e -> 7 state: 3 -> 3 retry: 4
01-08 19:58:20.248: D/Message:(1202): IOException occurred.

此外,如果我将文件夹放入我的存档中,代码zis.getNextEntry()将返回null。为什么会这样?为什么我不能读取档案中的两个文件?

2 个答案:

答案 0 :(得分:0)

既然您只是在寻求指导,而没有具体的问题。我只想回答一下zipinputstream

答案 1 :(得分:-1)

 prefix -> filename
 suffix -> extension
 File file = File.createTempFile(prefix, suffix)

 directory -> directory(File)[It may be necessary to set this property to an existing, writable directory for this method to work properly]
 File file = File.createTempFile(prefix, suffix, directory)