Javaがファイルを読み込む方法は、インターネット上で非常に詳しく説明されているので、ここでは紹介しません。
この記事では、ファイル内のデータを必要なデータ型に格納する方法を主に紹介します。文字列の配列として保存する場合は、配列のサイズを定義する必要があるため、最初にファイル内の総行数を取得する必要があります。ジェネリック クラスを使用してデータを保存すると、この手順が省略され、より柔軟になります。と便利に使用できます。
1. 文字列配列 (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]);
}
2. ジェネリック クラス (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]);
}
場合によっては、読み取り中にデータの行を処理できます。その後、配列またはジェネリックを使用して目的を達成できます。ジェネリックを配列に変換する必要はありません。