/************************************************** * Author: Morrison * Date: 20 Oct 202020 **************************************************/ import javafx.application.Application; import javafx.application.Platform; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.control.TextArea; import java.io.File; import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; public class FileViewer extends Application { private File file; private Stage primary; private TextArea ta; public FileViewer() { file = null; ta = new TextArea(); ta.setStyle("-fx-font-family:Courier"); } @Override public void init() { } @Override public void start(Stage primary) { this.primary = primary; primary.setTitle("FileViewer: No File Open"); BorderPane bp = new BorderPane(); HBox controls = new HBox(); bp.setTop(controls); buildControls(controls); bp.setCenter(ta); ta.setEditable(false); primary.setScene(new Scene(bp, 800, 600)); primary.show(); } private void buildControls(HBox box) { TextField tf = new TextField(); tf.setStyle("-fx-font-family:Courier"); Button goButton = new Button("GO!"); Button quitButton = new Button("Quit"); quitButton.setOnAction( e -> Platform.exit()); goButton.setOnAction( e -> { //file gets selected and put String fileName = tf.getText(); file = new File(fileName); String contents = getFileContents(fileName); primary.setTitle(String.format("FileViewer: %s", file.getAbsolutePath())); ta.setText(getFileContents(fileName)); }); box.getChildren().addAll(tf, goButton, quitButton); } private String getFileContents(String fileName) { file = new File(fileName); if(! file.exists()) { return String.format("File %s is a heffalump!\n", file.getAbsolutePath()); } try { StringBuffer sb = new StringBuffer(); if(file.isFile()) { BufferedReader br = new BufferedReader(new FileReader(file)); br.lines().forEach( line -> sb.append(line + "\n")); br.close(); } else if(file.isDirectory()) { sb.append(String.format("Contents of %s:\n", file.getName())); File[] files = file.listFiles(); for( File f : files) { sb.append(f.getName() + "\n"); } } return sb.toString().replace("\t", " "); } catch(IOException ex) { ex.printStackTrace(); return String.format("File %f is mooned by IOException!\n", file.getAbsolutePath()); } } //fileName will be a directory's name private String listDirectoryContents(String fileName) { return ""; } @Override public void stop() { } }