Вопрос

I'm trying to import a list of words into an arraylist from a .txt file. Right now i'm placing my .txt file into the assets folder. So far i can do this using the following code

try {
        AssetManager am = this.getAssets();
        InputStream inputStream = am.open(inputFile);

        if (inputStream != null) {
            InputStreamReader streamReader = new InputStreamReader(
                    inputStream);
            BufferedReader bufferedReader = new BufferedReader(streamReader);

            String line;

            while ((line = bufferedReader.readLine()) != null) {
                words.add(line);
            }
        }

        inputStream.close(); // close the file
    } catch (IOException e) {
        e.printStackTrace();
    }

I then want to be able to shuffle my arraylist and put the words back into the same .txt file, so that the next time I open the app it will import the shuffled list. But it turns out you can't write to files in the asset folder. Is there a different way to import words from a .txt file and still be able to export to that same .txt file? Where do I need to put my .txt file?

Это было полезно?

Решение

1) Place your txt file in assets.

2) At the first launch copy your txt file from assets to internal storage

Get InputStream of file in assets:

InputStream inputStream = am.open(inputFile);

Get OutputStream of file in internal storage:

File f = context.getFileStreamPath("filename.txt");
OutputStream outputStream = new FileOutputStream(f);

Copy data from input stream to output stream:

ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 8);

ReadableByteChannel ich = Channels.newChannel(inputStream);
WritableByteChannel och = Channels.newChannel(outputStream);

while (ich.read(buffer) > -1 || buffer.position() > 0)
{
    buffer.flip();
    och.write(buffer);
    buffer.compact();
}   
ich.close();
och.close();

3) Read data from internal storage:

File f = context.getFileStreamPath("filename.txt");
FileReader fr = new FileReader(f);
int chr = fr.read(); // read char
fr.close();

4) Write data to internal storage:

File f = context.getFileStreamPath("filename.txt");
FileWriter fw = new FileWriter(f);
fw.write("word"); // write string
fw.close();

You can use BufferedReader instead of FileReader for read file line by line.

Другие советы

You can not write into the file of assets folder because they are the read only files. You can only read it can't modify or update it into assets folder.

Keep in mind that all the resources of assets or drawables,values,xml are only read only files. It can not be modified.

So its better you copy your file into the sdcard and then modify it into external storage and then read it.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top