有没有办法在java Scanner中使用Variable而不是路径

时间:2014-01-15 03:11:24

标签: java file java.util.scanner jfilechooser

如何读取分配给使用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);
        }

            }

2 个答案:

答案 0 :(得分:2)

  

“因为我正在尝试使用JFileChoosear选择文件”

如果JFileChooser是返回值,则File将返回APPROVE_OPTION个对象。您可以使用chooser.getSelectedFile(),然后将其传递给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();
}

运行此

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

答案 1 :(得分:1)

你可以像这样传入一个字符串:

Scanner sc = new Scanner(new file(new String("/path/to/file.txt));