我在javaFX中编写代码来打开一个文本文件,我的代码打开它但它没有在文本文件中显示任何内容。而且只是为了好玩,我想知道什么是编辑文本文件然后用用户刚刚编辑的文本文件保存的最佳方法。任何提示将不胜感激。
这是我的代码:
package blah;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.stage.FileChooser;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.scene.control.Button;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import java.io.File;
public class blah
extends Application {
private Text actionStatus;
private Stage savedStage;
public static void main(String [] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
Button open = new Button("open");
open.setOnAction(new SingleFcButtonListener());
HBox open1 = new HBox(10);
open1.getChildren().addAll(open);
Button save = new Button("Save");
HBox save1 = new HBox(10);
save1.getChildren().addAll(save);
actionStatus = new Text();
VBox vbox = new VBox(30);
vbox.getChildren().addAll( open1,save1, actionStatus);
Scene scene = new Scene(vbox, 500, 300);
primaryStage.setScene(scene);
primaryStage.show();
savedStage = primaryStage;
}
private class SingleFcButtonListener implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent e) {
showSingleFileChooser();
}
}
private void showSingleFileChooser() {
FileChooser fileChooser = new FileChooser();
File selectedFile = fileChooser.showOpenDialog(null);
if (selectedFile != null) {
actionStatus.setText("File selected: " + selectedFile.getName());
}
}
}
答案 0 :(得分:2)
您可以使用 BufferedReader 或扫描程序来阅读文件:
<强>的BufferedReader 强>:
try (BufferedReader reader = new BufferedReader(new FileReader(new File("file.txt")))) {
String line;
while ((line = reader.readLine()) != null)
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}
<强>扫描仪强>:
try (Scanner scanner = new Scanner(new File("file.txt"))) {
while (scanner.hasNext())
System.out.println(scanner.next());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
您可以使用 PrintWriter 或 FileWriter (使用BufferedWriter)写入文件:
<强> FileWriter的强>:
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.flush();
bw.close();
示例here:
<强>的PrintWriter 强>:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.flush();
writer.close();
取自here