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

dojqjjoe  于 2023-06-28  发布在  Java
关注(0)|答案(7)|浏览(106)

我想从文本文件中读取文本。在下面的代码中,发生了一个异常(这意味着它进入了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();
    }
xmq68pz9

xmq68pz91#

试试这个:
我假设你的文本文件在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());

以下链接也可以帮助您:
How can I read a text file from the SD card in Android?
How to read text file in Android?
Android read text raw resource file

nqwrtyyt

nqwrtyyt2#

如果你想从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);

Good example of reading text file from res/raw folder

sh7euo9m

sh7euo9m4#

试试这个代码

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;
}
camsedfj

camsedfj5#

小文本文件的最短形式(Kotlin中):

val reader = FileReader(path)
val txt = reader.readText()
reader.close()
ckx4rj1h

ckx4rj1h6#

试试这个

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);
  }
xurqigkl

xurqigkl7#

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" />

相关问题