编写的public static String[] readStudentsFromFile(String fileName),把文件中的信息读取到String数组中
时间: 2024-05-01 15:21:18 浏览: 15
可以使用Java中的File、Scanner和ArrayList类来实现读取文件中的信息到String数组中。
具体步骤如下:
1. 创建一个空的ArrayList对象,用于存储文件中读取的信息。
2. 使用File类创建一个文件对象,指定要读取的文件名。
3. 使用Scanner类读取文件中的信息。可以使用Scanner类的hasNextLine()和nextLine()方法逐行读取文件中的信息,并将读取到的行添加到ArrayList对象中。
4. 将ArrayList对象转换为String数组。
5. 关闭Scanner对象。
下面是一个示例代码:
```java
public static String[] readStudentsFromFile(String fileName) {
ArrayList<String> students = new ArrayList<String>();
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
students.add(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String[] studentsArray = new String[students.size()];
studentsArray = students.toArray(studentsArray);
return studentsArray;
}
```
在上面的代码中,我们使用了try-catch语句来处理文件不存在的异常。如果文件不存在,会打印出堆栈跟踪信息。如果文件存在,会将文件中的每一行存储在ArrayList对象中,并最终将ArrayList对象转换为String数组返回。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)