流れとしては、
①メニューの「開く」ボタンを押下する。
②FileChooserを用いてファイルを選択する。
③選択したファイルのデータがTextAreaに表示される。
です。下記の内容で実装してみました。
【FXMLDocumentControllerクラス】FileChooserを呼び出し、戻り値のFileをUTF-8で読み込み、値をTextAreaにセットします。ついでに、ウィンドウの下の方にファイル名が表示されるようにしました。
public class FXMLDocumentController implements Initializable {
private ProcessManager pm;
private Scene scene;
private void openAction(ActionEvent event) {
bottomLabel.setText("開く");
File selectedFile = pm.openFileChooser(scene);
if(selectedFile != null) {
try {
textArea.setText(new String(Files.readAllBytes(Paths.get(selectedFile.getAbsolutePath())), StandardCharsets.UTF_8.name()));
} catch(IOException e) {
e.printStackTrace();
}
bottomLabel.setText(selectedFile.getName());
}
}
}
【ProcessManagerクラス】拡張子のフィルター機能がありますが、今回は一旦、「すべてのファイル」としておきました。
public class ProcessManager extends Application {
public File openFileChooser(Scene scene) {
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("すべてのファイル", "*.*")
);
File selectedFile = fileChooser.showOpenDialog(scene.getWindow());
return selectedFile;
}
}

↓

という事で、UTF-8ならちゃんとファイルを開くことができるプログラムができました。
0 件のコメント:
コメントを投稿