如何使用Jfilechooser从文本文件中使用数据

时间:2014-11-29 02:39:12

标签: java

我正在尝试使用程序中文本文件中的值,但首先我想真正了解如何使用JFileChooser,但我无法使其工作。

该计划:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JFileChooser;
public class Hw7Problem2 {
    public static void main(String[] args) throws FileNotFoundException {
        JFileChooser student_scores = new JFileChooser();
        int jfcUserOption = student_scores.showOpenDialog(null);
        // To verify it reads
        if (jfcUserOption == JFileChooser.APPROVE_OPTION) {
            File chosenFile = student_scores.getSelectedFile();
            System.out.println("The file you chose was: " + chosenFile.getName());
        }
        Scanner scanner = new Scanner(new File("student_scores.txt"));
        // Print text file on program
        System.out.println(scanner);
    }
}

错误:

The file you chose was: student_scores.txt
Exception in thread "main" java.io.FileNotFoundException: student_scores.txt (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.util.Scanner.<init>(Unknown Source)
    at Hw7Problem2.main(Hw7Problem2.java:21)

1 个答案:

答案 0 :(得分:6)

在创建扫描仪之前,您正确执行此操作。问题是您没有使用JFileChooser的结果。看起来您将结果放在chosenFile中。 getSelectedFile()将返回所选文件,因此您只需使用它创建扫描程序。

如果您需要了解有关JFileChooser如何工作的更多信息,可以在线查找文档here