简体   繁体   中英

android text file import where do i save text file what folder?

So this is a pretty embarrassing question, but i have a text file and java will read all of the words in it and add it to a array, i don't know where to put the text file, like what folder so the comp can go get it? could someone tell me. my code works in a regular java application, so it should work on android.

you can use

<your-context>.getAssets();

to return an AssetsManager object.

AssetsManager assets = context.getAssets();

You can then open an input stream with the open() method.

InputStream inputStream = assets.open("filename");

The InputStream object is a standard Java object from the IO package. You can decorate this stream with an object decorator you wish (Reader, BufferedReader, etc).

If you wish to move this file out of the APK (that is not inflated) to the phone you can just copy the bytes of the file from the input stream using an output stream. Note you will have to have permissions in your write directory (you can do this if your phone is rooted and you have created a shell interface to run native shell commands through JNI).

UPDATE

try {
    InputStream inputStream = this.getAssets().open("test.txt");
    BufferedReader buffer = new BufferedReader(new Reader(inputStream));

    String line;
    while((line = buffer.readLine()) != null) {
        tots.add(line);
    }
}
catch(IOException e) {
    e.printStackTrace();
}

Haven't tested it, but I think this is what you want.

I created new raw folder in res folder and put chapter0.txt in here.

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.induction);

    wordss = new Vector<String>();

    TextViewEx helloTxt = (TextViewEx) findViewById(R.id.test);
    helloTxt.setText(readTxt());
}

private String readTxt() {

    InputStream inputStream = getResources().openRawResource(R.raw.chapter0);
    // getResources().openRawResource(R.raw.internals);
    System.out.println(inputStream);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    int i;
    try {
        i = inputStream.read();
        while (i != -1) {
            byteArrayOutputStream.write(i);
            i = inputStream.read();
        }
        inputStream.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return byteArrayOutputStream.toString();
}

You can put the file to assets folder and use

InputStream stream = getAssets().open(filename); 

to get the input stream

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM