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