文件在桌面放着名字为hello.txt,先看一下要读取的内容
这是为了方便展示demo随便写的,格式是一行一个英文单词,一共五个。
读取代码,这个代码也是网上找的,忘了哪个博客了。
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author :
* @date : 2018/8/30
* @description:
*/
public class ReaderFileLine {
/**
* @author:
* @date:2018/8/30
* @description:从txt文件读取List<String>
*/
public static List<String> getFileContent(String path) {
List<String> strList = new ArrayList<String>();
File file = new File(path);
InputStreamReader read = null;
BufferedReader reader = null;
try {
read = new InputStreamReader(new FileInputStream(file),"utf-8");
reader = new BufferedReader(read);
String line;
while ((line = reader.readLine()) != null) {
strList.add(line);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (read != null) {
try {
read.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return strList;
}
public static void main(String[] args) {
List<String> fileContent =
ReaderFileLine.getFileContent("C:\\Users\\Lenovo\\Desktop\\hello.txt");
for (String s : fileContent) {
System.out.println(s);
}
}
}
输出:
first
second
Third
Fourth
Fifth
注意:
1.这里File这个类导入的包是Io的,不是Nio的
2. ReaderFileLine.getFileContent("C:\\Users\\Lenovo\\Desktop\\hello.txt"); 这个路径是绝对路径
3.路径是一个 反斜杠 \ 但是在代码里面反斜杠是转义的意思,所以需要再加一个\,如果你是用的IDEA恭喜你,它会自动给你加上
如果你用的java8推荐这种方式:https://blog.youkuaiyun.com/Mint6/article/details/82227871