Сканер, выберите файл на компьютере - PullRequest
0 голосов
/ 14 июля 2020

Теперь я прочитал свой .txt файл, сообщив, где этот файл. Я хочу изменить на "Я могу выбрать файл на моем компьютере". Как я могу это сделать?

Scanner file = new Scanner(new File("Sample.txt"));

while (file.hasNextLine()) {
    String input = file.nextLine();
}

Ответы [ 2 ]

2 голосов
/ 14 июля 2020

Вот исполняемый файл, который вы можете попробовать. Как и предусмотрено @Verity, используйте JFileChooser . Прочтите комментарии в следующем коде:

public class JFileChooserWithConsoleUse {

    public static void main(String[] args) {
        // A JFrame used here as a backbone for dialogs
        javax.swing.JFrame iFrame = new javax.swing.JFrame();
        iFrame.setDefaultCloseOperation(javax.swing.JFrame.DISPOSE_ON_CLOSE);
        iFrame.setAlwaysOnTop(true);
        iFrame.setLocationRelativeTo(null);
    
        String selectedFile = null;
        javax.swing.JFileChooser fc = new javax.swing.JFileChooser(new java.io.File("C:\\"));
        fc.setDialogTitle("Locate And Select A File To Read...");
        int userSelection = fc.showOpenDialog(iFrame);
    
        // The following code will not run until the 
        // FileChooser dialog window is closed.
        iFrame.dispose();   // Dispose of the JFrame.
        if (userSelection == 0) { 
            selectedFile = fc.getSelectedFile().getPath();
        }

        // If no file was selected (dialog just closed) then 
        // get out of this method (which in this demo ultimately
        // ends (closes) the application.
        if (selectedFile == null) {
            javax.swing.JOptionPane.showMessageDialog(iFrame, "No File Was Selected To Process!",
                                    "No File Selected!", javax.swing.JOptionPane.WARNING_MESSAGE);
            iFrame.dispose();   // Dispose of the JFrame.
            return;
        }
    
        // Read the selected file... 'Try With Resources' is 
        // used here so as to auto-close the reader. 
        try (java.util.Scanner file = new java.util.Scanner(new java.io.File(selectedFile))) {
            while (file.hasNextLine()) {
                String input = file.nextLine();
                // Display each read line in the Console Window.
                System.out.println(input);
            }
        }
        catch (java.io.FileNotFoundException ex) {
            System.err.println(ex);
        }
    }
}
0 голосов
/ 14 июля 2020

В этом случае вам нужно использовать JFileChooser

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...