在android中读取文件

时间:2017-04-19 09:41:20

标签: android

我正在编写一个Android应用程序,我试图从我在assets文件夹的main文件夹中添加的数据库中读取。但是我收到错误file not found exception

public File database = new File("/assets/GeoIP2.mmdb");


PS:这是一个数据库文件而不是文本文件。

4 个答案:

答案 0 :(得分:0)

这是从资源文件夹

中读取文件的正确方法
MyModel.objects.filter(Q(a=0) | Q(a__exact=F('b')))

答案 1 :(得分:0)

你可以尝试下面的代码,它的工作100%

private String readFromFile(String name) {

    String ret = "";

    try {
        InputStream inputStream = getAssets().open(name + ".txt");

        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ((receiveString = bufferedReader.readLine()) != null) {
                stringBuilder.append(receiveString);
                stringBuilder.append("\n");
            }

            inputStream.close();
            ret = stringBuilder.toString();
        }
    } catch (FileNotFoundException e) {
        Log.e(TAG, "File not found: " + e.toString());
    } catch (IOException e) {
        Log.e(TAG, "Can not read file: " + e.toString());
    }

    return ret;
}

只需更改文件格式而不是.txt

答案 2 :(得分:0)

InputStream is = getAssets()。open(“thirukkuralxml.xml”);

答案 3 :(得分:-1)

 try{
            String verify, putData;
            File file = new File("file.txt");
            file.createNewFile();
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("Some text here for a reason");
            bw.flush();
            bw.close();
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);

            while( (verify=br.readLine()) != null ){ //***editted
                       //**deleted**verify = br.readLine();**
                if(verify != null){ //***edited
                    putData = verify.replaceAll("here", "there");
                    bw.write(putData);
                }
            }
            br.close();


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