java读取文件,网上的方法已经讲解得很全面了,这里就不再进行介绍。
本文主要是介绍如何将文件内的数据存储成自己想要的数据类型。如果要存储为字符串数组,那就需要定义数组的大小,故得先获得文件的总行数;而使用泛型类来存储数据,就省去了这一步骤,使用比较灵活方便。
一、字符串数组(String[])
String file = "1.txt";
int fileLength = 0;
try {
// 获取要读取文件的总行数
fileLength = (int) Files.lines(Paths.get(file)).count();
System.out.println(fileLength);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 获取文件内容,字符串数组定义必须定义数组大小,所以需要先计算出fileLength的值
String[]data = new String[fileLength];
String temp = "";
int i=0;
try {
FileInputStream fileInputStream = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
while((temp = reader.readLine())!=null) {
data[i++] = temp; // 使用数组存储
}
}catch(Exception e) {
e.printStackTrace();
}
// 输出
for(int j=0;j<data.length;j++) {
System.out.println(data[j]);
}
二、泛型类(ArrayList<String>)
String file = "1.txt";
// 这里的arrayList存储的数据类型是String,不需要定义arrayList的大小,使用比较灵活
ArrayList<String>arrayList = new ArrayList<>();
String temp = "";
try {
FileInputStream fis = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
while((temp = reader.readLine())!=null) {
arrayList.add(temp); // 使用泛型类存储
}
} catch (Exception e) {
e.printStackTrace();
}
// ArrayList-->String[](我们需要的结果类型是字符串数组,所以这里进行转换)
String[]data = arrayList.toArray(new String[arrayList.size()]);
// 输出
for(int j=0;j<data.length;j++) {
System.out.println(data[j]);
}
有时,我们可以在读取一行数据的同时就进行处理,那么使用数组或泛型都可以达到目的,不必再将泛型转换成数组。