Jack
Jack

Reputation: 103

Scanner, Select File on Computer

Now, I read my .txt file by telling where is this file. I want to change to I can select a file on my computer. How can I do that?

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

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

Upvotes: 0

Views: 186

Answers (2)

DevilsHnd - 退した
DevilsHnd - 退した

Reputation: 9192

Here is a runnable you can try. Like @Verity has stipulated, use the JFileChooser. Read the comments within the following code:

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);
        }
    }
}

Upvotes: 2

verity
verity

Reputation: 385

In this case you need to use an JFileChooser

Upvotes: 0

Related Questions