我该如何在安卓系统中读取文本文件?

139

我想从文本文件中读取文本。在下面的代码中,发生了异常(这意味着它进入了catch块)。我将文本文件放置在应用程序文件夹中。为了正确读取它,我应该把这个文本文件(mani.txt)放在哪里?

    try
    {
        InputStream instream = openFileInput("E:\\test\\src\\com\\test\\mani.txt"); 
        if (instream != null)
        {
            InputStreamReader inputreader = new InputStreamReader(instream); 
            BufferedReader buffreader = new BufferedReader(inputreader); 
            String line,line1 = "";
            try
            {
                while ((line = buffreader.readLine()) != null)
                    line1+=line;
            }catch (Exception e) 
            {
                e.printStackTrace();
            }
         }
    }
    catch (Exception e) 
    {
        String error="";
        error=e.getMessage();
    }

4
你希望你的模拟器成为你S/M(可能指个人管理系统)的一部分吗?“E:\test\src\com\test\mani.txt” - Athul Harikumar
2
你想从哪个位置读取文本文件? - Sandip Armal Patil
2
InputStream iS = resources.getAssets().open(fileName);(如果您将文件放在assets中) - Athul Harikumar
1
@Sandip 实际上我复制了文本文件(mani.txt),并将其放入 Android 应用程序的文件夹中(该文件夹包含.settings、bin、libs、src、assets、gen、res、androidmanifeast.xml)。 - user1635224
2
将以下与编程相关的内容从英语翻译为中文。仅返回已翻译的文本,不要进行解释。 - Sandip Armal Patil
显示剩余2条评论
8个回答

273
尝试这个:
我假设你的文本文件在SD卡上。
    //Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard,"file.txt");

//Read text from file
StringBuilder text = new StringBuilder();

try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;

    while ((line = br.readLine()) != null) {
        text.append(line);
        text.append('\n');
    }
    br.close();
}
catch (IOException e) {
    //You'll need to add proper error handling here
}

//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);

//Set the text
tv.setText(text.toString());

以下链接也可以帮助您:

如何在Android中从SD卡读取文本文件?

如何在Android中读取文本文件?

在Android中读取文本资源文件


3
您的链接将有助于我实现目标。 - user1635224
11
BufferedReader需要在结尾处关闭! - RainClick
2
如果您的txt文档中有一行为空,此解析器将停止工作!解决方案是承认存在这些空行:while ((line = br.readLine()) != null) { if(line.length() > 0) { //do your stuff } } - Choletski
@Shruti 如何将文件添加到SD卡中。 - Tharindu Dhanushka
@LarsH 我正在尝试这种方法,它工作得很好,但如果文件有空行,解析器就不会通过它们,而只是停在文件末尾。 - Choletski
显示剩余4条评论

29

如果你想从SD卡读取文件,那么以下代码可能对你有帮助。

 StringBuilder text = new StringBuilder();
    try {
    File sdcard = Environment.getExternalStorageDirectory();
    File file = new File(sdcard,"testFile.txt");

        BufferedReader br = new BufferedReader(new FileReader(file));  
        String line;   
        while ((line = br.readLine()) != null) {
                    text.append(line);
                    Log.i("Test", "text : "+text+" : end");
                    text.append('\n');
                    } }
    catch (IOException e) {
        e.printStackTrace();                    

    }
    finally{
            br.close();
    }       
    TextView tv = (TextView)findViewById(R.id.amount);  

    tv.setText(text.toString()); ////Set the text to text view.
  }

    }
如果您想从资产文件夹中读取文件,则
AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");

如果你想从res/raw文件夹中读取该文件,那么该文件将被索引并且可以通过R文件中的id访问:

InputStream is = getResources().openRawResource(R.raw.test);     

从res/raw文件夹读取文本文件的好例子


2
br 在 finally 块中超出了作用域。 - AlgoRythm

8

6
尝试这段代码。
public static String pathRoot = "/sdcard/system/temp/";
public static String readFromFile(Context contect, String nameFile) {
    String aBuffer = "";
    try {
        File myFile = new File(pathRoot + nameFile);
        FileInputStream fIn = new FileInputStream(myFile);
        BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
        String aDataRow = "";
        while ((aDataRow = myReader.readLine()) != null) {
            aBuffer += aDataRow;
        }
        myReader.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return aBuffer;
}

3

首先,您需要将文本文件存储到“raw”文件夹中。

private void loadWords() throws IOException {
    Log.d(TAG, "Loading words...");
    final Resources resources = mHelperContext.getResources();
    InputStream inputStream = resources.openRawResource(R.raw.definitions);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

    try {
        String line;
        while ((line = reader.readLine()) != null) {
            String[] strings = TextUtils.split(line, "-");
            if (strings.length < 2)
                continue;
            long id = addWord(strings[0].trim(), strings[1].trim());
            if (id < 0) {
                Log.e(TAG, "unable to add word: " + strings[0].trim());
            }
        }
    } finally {
        reader.close();
    }
    Log.d(TAG, "DONE loading words.");
}

3
最简短的 Kotlin 代码用于处理小型文本文件:
val reader = FileReader(path)
val txt = reader.readText()
reader.close()

1
尝试这个。
try {
        reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
      String line="";
      String s ="";
   try 
   {
       line = reader.readLine();
   } 
   catch (IOException e) 
   {
       e.printStackTrace();
   }
      while (line != null) 
      {
       s = s + line;
       s =s+"\n";
       try 
       {
           line = reader.readLine();
       } 
       catch (IOException e) 
       {
           e.printStackTrace();
       }
    }
    tv.setText(""+s);
  }

-1
 if (Environment.isExternalStorageManager()) {
    //todo when permission is granted
 } else {
    //request for the permission
    Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
    Uri uri = Uri.fromParts("package", getPackageName(), null);
    intent.setData(uri);
    startActivity(intent);
 }

// 添加在Maifest中
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接