public boolean addNewStudent(String[] student,int file) { StringBuffer studnetOneString = new StringBuffer(); this.readin(studentManager.studentFile[file-1]); this.studentList.add(student); for (String[] studentOneArray : studentList) { for (String studnetOne : studentOneArray) { studnetOneString.append(studnetOne + ";"); } studnetOneString.append("\n"); } ByteArrayInputStream stream = null; stream = new ByteArrayInputStream(studnetOneString.toString().getBytes()); try { OutputStream os = new FileOutputStream(studentManager.studentFile[file-1]); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); stream.close(); studentList = null; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return true; }
时间: 2024-03-29 12:35:45 浏览: 22
这段代码是一个方法,它的作用是向学生列表中添加一个新的学生信息,并将这个信息写入到指定的文件中。具体实现如下:
首先,创建一个StringBuffer对象studnetOneString,用于存储所有学生信息的字符串。然后调用readin方法读取指定文件中的所有学生信息,并将它们存储在studentList中。接着,向studentList中添加新的学生信息。这个新的学生信息是由一个String数组student表示的,它包含了学生的各个属性,例如姓名、学号、专业、费用等。
接下来,通过for-each循环遍历studentList中的每一个学生信息,将它们转换成一个字符串,并将这个字符串添加到studnetOneString中。这个字符串的格式是将每个属性用“;”分隔开来,并在每个学生信息的结尾添加一个换行符“\n”。
然后,创建一个ByteArrayInputStream对象stream,将studnetOneString转换成一个字节数组,并将这个字节数组作为stream的初始值。接着,创建一个输出流OutputStream os,将要写入的文件名作为参数传递给它。然后,创建一个缓冲区byte[] buffer,用于读取stream中的字节数据。接着,通过while循环不断地从stream中读取字节数据,并将这些数据写入到输出流os中。当读取到的字节数为-1时,表示已经读取完全部数据,此时退出循环。最后,关闭输入流stream和输出流os,并将studentList引用置为null。
最后,这个方法返回一个布尔值,表示添加新学生信息是否成功。如果成功添加新学生信息并将其写入到文件中,方法返回true,否则返回false。
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)