JavaFX教师工资管理系统,文件存储
时间: 2023-12-26 10:26:40 浏览: 32
JavaFX教师工资管理系统可以使用Java提供的文件存储API来进行文件存储。常用的文件存储方式有两种:文本文件和二进制文件。文本文件可以使用Java提供的Reader和Writer类进行读写,而二进制文件可以使用Java提供的InputStream和OutputStream类进行读写。在JavaFX中,可以使用FileChooser类来选择文件进行读写操作。以下是一个简单的JavaFX文件读写的例子:
```java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
public class FileReadWriteExample extends Application {
private TextArea textArea;
@Override
public void start(Stage primaryStage) throws Exception {
textArea = new TextArea();
Button openButton = new Button("Open");
openButton.setOnAction(e -> openFile());
Button saveButton = new Button("Save");
saveButton.setOnAction(e -> saveFile());
VBox root = new VBox(textArea, openButton, saveButton);
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
private void openFile() {
FileChooser fileChooser = new FileChooser();
File file = fileChooser.showOpenDialog(null);
if (file != null) {
try (Scanner scanner = new Scanner(file)) {
StringBuilder sb = new StringBuilder();
while (scanner.hasNextLine()) {
sb.append(scanner.nextLine()).append("\n");
}
textArea.setText(sb.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void saveFile() {
FileChooser fileChooser = new FileChooser();
File file = fileChooser.showSaveDialog(null);
if (file != null) {
try (FileWriter writer = new FileWriter(file)) {
writer.write(textArea.getText());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
launch(args);
}
}
```
该例子中,我们使用了JavaFX提供的FileChooser类来选择文件进行读写操作。在openFile()方法中,我们使用Scanner类来读取文件内容,并将其显示在TextArea中。在saveFile()方法中,我们使用FileWriter类来将TextArea中的内容写入文件中。需要注意的是,在使用完文件读写API后,需要关闭文件流,以释放资源。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)