gpt4 book ai didi

java - 有没有办法在java Scanner中使用变量而不是路径

转载 作者:行者123 更新时间:2023-12-01 23:16:27 24 4
gpt4 key购买 nike

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

}

最佳答案

" because i am trying to select file using JFileChoosear "

如果返回值是 APPROVE_OPTION,则 JFileChooser 将返回一个 File 对象。您可以使用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();
}
}
}

关于java - 有没有办法在java Scanner中使用变量而不是路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21128440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com