简体   繁体   English

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

[英]How to use data from text file using Jfilechooser

I am trying to use the values from a text file in my program, but first I would like to really understand how to use JFileChooser which I cannot make it work. 我试图在程序中使用文本文件中的值,但是首先我想真正地了解如何使用JFileChooser ,但我无法使其工作。

The program: 该程序:

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 error: 错误:

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)

You are doing this correctly until you create the scanner. 您必须正确执行此操作,直到创建扫描仪。 The problem is that you aren't using the result of the JFileChooser. 问题是您没有使用JFileChooser的结果。 It looks like you put the result in chosenFile . 看起来您将结果放入chosenFile getSelectedFile() will return the file that was chosen, so you just need to create the scanner with it. getSelectedFile()将返回所选的文件,因此您只需要使用它创建扫描程序。

If you need to understand more about how the JFileChooser works, you can find the documentation online here . 如果您需要了解有关JFileChooser如何工作的更多信息,可以在此处在线找到文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM