Question

how to read file that assigned to reference variable selected using JFileChooser

package AnimeAid;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;

    public class ReadFile {
        private File ourFile;
              Scanner sc;

        public ReadFile() {
            this.sc = new Scanner(new File(ourFile);
        }

            }
Was it helpful?

Solution

" because i am trying to select file using JFileChoosear "

The JFileChooser will return a File object if APPROVE_OPTION is the return value. You can use chooser.getSelectedFile() then pass it to the Scanner

JFileChooser chooser = new JFileChooser();

File file = null;
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
    file = chooser.getSelectedFile();
}

try {
    Scanner scanner = new Scanner(file);
    // read file
} catch (Exception ex) {
    ex.printStackTrace();
}

Run this

import java.io.File;
import java.util.Scanner;
import javax.swing.JFileChooser;

public class TestFileChooser {

    public static void main(String[] args) {
        JFileChooser chooser = new JFileChooser();

        File file = null;
        int returnVal = chooser.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            file = chooser.getSelectedFile();
        }

        try {
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                System.out.println(scanner.nextLine());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

OTHER TIPS

You can pass in a string like so:

Scanner sc = new Scanner(new file(new String("/path/to/file.txt));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top