這幾天在項目開發中,要讀取文本文件中內容的,因此寫了個讀取文本文件中內容的方法,代碼如下:
//讀取文本文件中的內容
public static String ReadTxtFile(String strFilePath)
{
String path = strFilePath;
String content = ""; //文件內容字符串
//打開文件
File file = new File(path);
//如果path是傳遞過來的參數,可以做一個非目錄的判斷
if (file.isDirectory())
{
Log.d("TestFile", "The File doesn't not exist.");
}
else
{
try {
InputStream instream = new FileInputStream(file);
if (instream != null)
{
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
//分行讀取
while (( line = buffreader.readLine()) != null) {
content += line + "\n";
}
instream.close();
}
}
catch (java.io.FileNotFoundException e)
{
Log.d("TestFile", "The File doesn't not exist.");
}
catch (IOException e)
{
Log.d("TestFile", e.getMessage());
}
}
return content;
}