File file = new File("data.txt"); try (PrintWriter writer = new PrintWriter(file)) { // 写入课程信息 for (int i = 0; i < courseModel.getRowCount(); i++) { String courseName = (String) courseModel.getValueAt(i, 0); String courseNo = (String) courseModel.getValueAt(i, 1); String credit = (String) courseModel.getValueAt(i, 2); writer.printf("%s,%s,%s%n", courseName, courseNo, credit); } // 写入学生成绩信息 for (Map.Entry<String, Map<String, String>> entry : scoreMap.entrySet()) { String studentId = entry.getKey(); Map<String, String> scoreMap = entry.getValue(); for (Map.Entry<String, String> scoreEntry : scoreMap.entrySet()) { String courseNo = scoreEntry.getKey(); String score = scoreEntry.getValue(); writer.printf("%s,%s,%s%n", studentId, courseNo, score); } } } catch (IOException e) { e.printStackTrace(); }
时间: 2024-01-21 22:03:43 浏览: 26
这段代码的作用是将课程信息和学生成绩信息写入到名为"data.txt"的文件中。其中,课程信息是从courseModel中获取,学生成绩信息是从scoreMap中获取。每行数据的格式为"课程名称,课程编号,学分"或"学生编号,课程编号,成绩"。写入操作是通过PrintWriter实现的。该代码还使用了Java 7中的try-with-resources语句,确保在写入完成后自动关闭PrintWriter并释放资源,同时也处理了可能出现的IO异常。
相关问题
根据以下要求:Instead of using a text file to save all the point coordinates one by one, change the savaData method and the constructor of the Model class to use object serialization and a binary file called "points.bin" to write / read the whole arraylist of points to / from the file in one operation.修改下述代码:import java.awt.Point; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class Model { private ArrayList<Point> points; private ArrayList<ModelListener> listeners; public Model() { points = new ArrayList<Point>(); listeners = new ArrayList<ModelListener>(); // Read points from file if it exists File file = new File("points.txt"); if (file.exists()) { try { Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String[] coordinates = scanner.nextLine().split(" "); int x = (int) Double.parseDouble(coordinates[0]); int y = (int) Double.parseDouble(coordinates[1]); points.add(new Point(x, y)); } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } } public void addListener(ModelListener l) { listeners.add(l); } public ArrayList<Point> getPoints() { return points; } public void addPoint(Point p) { points.add(p); notifyListeners(); // points changed so notify the listeners. saveData(); // save point to file } public void clearAllPoints() { points.clear(); notifyListeners(); // points changed so notify the listeners. saveData(); // save empty list to file } public void deleteLastPoint() { if (points.size() > 0) { points.remove(points.size() - 1); notifyListeners(); // points changed so notify the listeners. saveData(); // save updated list to file } } private void notifyListeners() { for (ModelListener l : listeners) { l.update(); // Tell the listener that something changed. } } public int numberOfPoints() { return points.size(); } public void saveData() { try { FileWriter writer = new FileWriter("points.txt"); for (Point p : points) { writer.write(p.x + " " + p.y + "\n"); } writer.close(); } catch (IOException e) { e.printStackTrace(); } }
以下是修改后的代码:
import java.awt.Point;
import java.io.*;
public class Model implements Serializable {
private ArrayList<Point> points;
private ArrayList<ModelListener> listeners;
private static final String FILE_NAME = "points.bin";
public Model() {
points = new ArrayList<Point>();
listeners = new ArrayList<ModelListener>();
// Read points from file if it exists
File file = new File(FILE_NAME);
if (file.exists()) {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
points = (ArrayList<Point>) in.readObject();
in.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
public void addListener(ModelListener l) {
listeners.add(l);
}
public ArrayList<Point> getPoints() {
return points;
}
public void addPoint(Point p) {
points.add(p);
notifyListeners(); // points changed so notify the listeners.
saveData(); // save point to file
}
public void clearAllPoints() {
points.clear();
notifyListeners(); // points changed so notify the listeners.
saveData(); // save empty list to file
}
public void deleteLastPoint() {
if (points.size() > 0) {
points.remove(points.size() - 1);
notifyListeners(); // points changed so notify the listeners.
saveData(); // save updated list to file
}
}
private void notifyListeners() {
for (ModelListener l : listeners) {
l.update(); // Tell the listener that something changed.
}
}
public int numberOfPoints() {
return points.size();
}
public void saveData() {
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(FILE_NAME));
out.writeObject(points);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这里我们使用了Java的序列化机制来保存整个ArrayList对象,同时将数据保存到了一个二进制文件中(名为"points.bin")。在构造函数中,我们首先检查是否存在该文件,如果存在,则通过ObjectInputStream读取该文件并将ArrayList对象恢复到程序中。在saveData()方法中,我们使用ObjectOutputStream将整个ArrayList对象写入文件。注意:我们还必须将Model类实现Serializable接口来支持序列化。
根据以下要求帮我修改上述代码:Add to the Model class a new method called savaData that saves into a text file called "points.txt" the integer coordinates x and y of each point in the arraylist of points. Also modify the constructor of the Model class to read the integer coordinates of all the points from the same text file, if it exists, and put them into the arraylist of points (if the file does not exist then the arraylist of points should remain empty).
好的,我可以帮您修改代码。请看下面的代码:
```
import java.util.ArrayList;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Model {
private ArrayList<Point> points;
public Model() {
points = new ArrayList<Point>();
try {
BufferedReader reader = new BufferedReader(new FileReader("points.txt"));
String line = reader.readLine();
while (line != null) {
String[] coords = line.split(",");
int x = Integer.parseInt(coords[0]);
int y = Integer.parseInt(coords[1]);
Point p = new Point(x, y);
points.add(p);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
// Do nothing if the file does not exist
}
}
public void addPoint(Point p) {
points.add(p);
}
public ArrayList<Point> getPoints() {
return points;
}
public void saveData() {
try {
PrintWriter writer = new PrintWriter("points.txt", "UTF-8");
for (Point p : points) {
writer.println(p.getX() + "," + p.getY());
}
writer.close();
} catch (IOException e) {
System.out.println("Error saving data to file.");
}
}
}
```
我添加了一个名为 `saveData()` 的新方法,它将点坐标写入名为 "points.txt" 的文件中。我还修改了构造函数,以从该文件中读取所有点的坐标,并将它们放入点列表中(如果文件不存在,则点列表应该保持为空)。