Why is it that I cant use split method on input
? In Eclipse it says: The method split(String) is undefined for the type Scanner. I dont know what I am doing wrong, if anyone could guide me in the right direction.
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();
}
}
}
});
Thanks.
You'd have to get a String
out of the Scanner
before trying to split()
it. You're probably looking for Scanner.next()
or Scanner.nextLine()
.
If you're trying to read a whole file in, you'll need to use a loop to read a line at a time until Scanner.hasNextLine()
returns false. Alternately, you could just read the whole file into a String
using commons-io FileUtils.readFileToString() .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.