- 在java编程过程中,我们可能有时遇到:要读取特定文件中的内容,并将文件中每一行读取为一个字符串,将所有字符串存储在字符串数组中的情况。我们可以直接采用以下函数实现:
public static List<String> readFile(String filePath)
{
List<String> sourceList = new ArrayList<String>();
File file = new File(filePath);
String encoding = "utf-8";
String line;
try
{
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, encoding);
BufferedReader br = new BufferedReader(isr);
int i = 0;
while( (line=(br.readLine()))!=null)
{
sourceList.add(line);
}
br.close(); isr.close(); fis.close();
}
catch(UnsupportedEncodingException e) { e.printStackTrace();}
catch(FileNotFoundException e) { e.printStackTrace();}
catch(IOException e) { e.printStackTrace();}
return sourceList;
}
- 其参数为要读取文件的路径,返回值为一个String类型的链表。
- 以上的代码可以直接复制,并调用,使用。