例子:
public class test2 {
public static String filePath="/Users/电脑/Desktop/kk.txt";
//第1种:普通方式:
public static void redFile() throws Exception{
//缓冲流 //字符转换流 //文件字节输入流
try(BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(filePath)))){
String data= null;
while (null != (data=br.readLine())){//遍历每一行打印
System.out.println("普通获取:"+data);
}
}catch (Exception e) {
e.printStackTrace();
}
}
//第2种:jdk8 Stream流式读取方式:
public static void streamRedFile() throws Exception{
try(Stream<String> stream= Files.lines(Paths.get(filePath), Charset.defaultCharset())){
stream.forEach(System.out::println);//函数式的写法
}
}
public static void main(String args[]) {
//读取文本的2种方式
//第1种
try {
redFile();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("-------------------------------------");
//第2种
try {
streamRedFile();
} catch (Exception e) {
e.printStackTrace();
}
}
}
打印:
普通获取:Asdsadas
普通获取:1111
普通获取:22222
普通获取:2333
普通获取:434343
-------------------------------------
Asdsadas
1111
22222
2333
434343
第三种:
public static ArrayList<String> readFromTextFile(String pathname) throws IOException {
ArrayList<String> strArray = new ArrayList<String>();
File filename = new File(pathname);
InputStreamReader reader = new InputStreamReader(new FileInputStream(filename));
BufferedReader br = new BufferedReader(reader);
String line = "";
line = br.readLine();
while(line != null) {
strArray.add(line);
line = br.readLine();
}
return strArray;
}
public static void main(String args[]) {
try {
ArrayList<String> list=readFromTextFile(filePath);
for (int i = 0; i < list.size(); i++) {
System.out.println("========="+list.get(i).toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
结果:
=========#in the frame Video positions
=========label_mask=65
=========#video position
=========#layout
=========label_number=72
=========# possible to define