gpt4 book ai didi

java - Scanner 类型的 split(String) 方法未定义

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

为什么我不能在input上使用split方法?在 Eclipse 中,它显示:对于 Scanner 类型,方法 split(String) 未定义。我不知道我做错了什么,是否有人可以指导我正确的方向。

btnFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {

JFileChooser chooser = new JFileChooser("C:\\");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

FileNameExtensionFilter filter = new FileNameExtensionFilter(
" Only .txt", "txt");
chooser.setFileFilter(filter);

int code = chooser.showOpenDialog(null);
if (code == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
Scanner input;
try {
input = new Scanner(selectedFile); // <-- Here
String[] splits = input.next().split(" "); <-- And here

for (int i = 0; i < splits.length; i++) {
textArea.setText(splits[i]);
System.out.println(splits[i]);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});

谢谢。

最佳答案

您必须获得 StringScanner在尝试split()之前它。您可能正在寻找Scanner.next()Scanner.nextLine() .

如果您尝试读取整个文件,则需要使用循环一次读取一行,直到 Scanner.hasNextLine()返回假。或者,您可以使用 commons-io FileUtils.readFileToString() 将整个文件读入 String 中。 .

关于java - Scanner 类型的 split(String) 方法未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15126448/

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