#java读取txt文件的第一种方法
/**
* 方法:readTxt
* 功能:读取txt文件并把txt文件的内容---每一行作为一个字符串加入到List中去
* 参数:txt文件的地址
* 返回:Map
* @param file
* @return
* @throws IOException
*/
public static Map readTxt(String file) throws IOException {
Map tempMap = new HashMap();
List allLines = Files.readAllLines(Paths.get(file));
//以下为我截取文件内容,一行分成2段,第一段设置为Map的Key,第二段设置为Map的Value
for (String line : allLines) {
if (line != "") {
String[] temp = line.split(" J:: ");
if (temp.length == 2) {
tempMap.put(temp[0], temp[1]);
}
}
}
return tempMap;
}
#读取txt文件的第二种方法
public Map read() throws Exception{
// List allLines = Files.readAllLines(Paths.get(File));
/*
通常,由读取器做出的每个读取请求将引起对底层字符或字节流的相应读取请求。
因此,建议将BufferedReader包装在其read()操作可能昂贵的读取器上,
例如FileReaders和InputStreamReaders
*/
FileReader fileReader = new FileReader(File);
BufferedReader bufferedReader = new BufferedReader(fileReader);
Map tempMap = new HashMap();
while((lines = bufferedReader.readLine()) != null)
{
list.add(lines);
}
bufferedReader.close();
//以下为我切割的规则,一行切成2段,第一段设置为Map的Key,第二段设置为Map的Value
for(String singleList : list)
{
if(singleList != "")
{
String[] temp = singleList.split( "J:: ");
if(temp.length == 2)
{
tempMap.put(temp[0],temp[1]);
}
}
}
return tempMap;
}