1. 使用`BufferedReader`和`FileReader`读取文件内容。
2. 使用`readLine`方法逐行读取文件内容。
3. 根据需要将每行内容分割成数组元素。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadTxtToArray {
public static void main(String[] args) {
String filePath = "path/to/your/file.txt"; // 替换为你的文件路径
String[] lines = readTxtFile(filePath);
for (String line : lines) {
System.out.println(line); // 打印每行内容
}
}
public static String[] readTxtFile(String filePath) {
String[] result = new String;
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
result = appendLineToArray(result, line);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private static String[] appendLineToArray(String[] array, String line) {
String[] newArray = new String[array.length + 1];
System.arraycopy(array, 0, newArray, 0, array.length);
newArray[array.length] = line;
return newArray;
}
}
如果你需要将每行的内容进一步分割成其他类型的数组(如整数数组),你可以使用`split`方法,例如:
public static int[] readIntArray(String filePath) {
int[] result = new int;
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
String[] numbers = line.split(" "); // 根据空格分割字符串
int[] newArray = new int[numbers.length];
for (int i = 0; i < numbers.length; i++) {
newArray[i] = Integer.parseInt(numbers[i]);
}
result = concatenateArrays(result, newArray);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private static int[] concatenateArrays(int[] firstArray, int[] secondArray) {
int[] result = new int[firstArray.length + secondArray.length];
System.arraycopy(firstArray, 0, result, 0, firstArray.length);
System.arraycopy(secondArray, 0, result, firstArray.length, secondArray.length);
return result;
}
请根据你的具体需求调整代码。