Reputation: 13
I am trying to scan through text files and add them to a map, the map and everything is working. However, the scanner seems to be stopping when it comes to a 'enter' in the text file, or a blank line. This is my problem
here is my block of code for the scanner/mapper
class OneButtonListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent evt)
{
final JFileChooser oneFC = new JFileChooser();
oneFC.showOpenDialog(AnalysisFrame.this);
String newLine = null;
oneFC.getName(null);
int returnVal = 0;
File fileOne = oneFC.getSelectedFile();
Scanner input = null;
try {
input = new Scanner(fileOne);
}
catch (FileNotFoundException ex) {
Logger.getLogger(AnalysisFrame.class.getName()).log(Level.SEVERE, null,
ex);
}
inputText = input.nextLine();
String[] words = inputText.split("[ \n\t\r,.;:!?(){}]");
for(int i = 0; i < words.length; i++){
key = words[i].toLowerCase();
if (words[i].length() > 1){
if (mapOne.get(key) == null){
mapOne.put(key, 1);
}
else {
value1 = mapOne.get(key).intValue();
value1++;
apOne.put(key, value1);
}
}
}
}
}
Thanks for any help!
Upvotes: 1
Views: 4270
Reputation: 7435
You should scan inside a loop until it reaches the end of the file, for example:
StringBuilder builder = new StringBuilder();
while(input.hasNextLine()){
builder.append(input.nextLine());
builder.append(" "); // might not be necessary
}
String inputText = builder.toString();
An alternative to using split
could be to use a Delimiter with the Scanner
and use hasNext()
and next()
instead of hasNextLine()
and nextLine()
. Try it out, see if it works.
For example:
scanner.useDelimiter("[ \n\t\r,.;:!?(){}]");
ArrayList<String> tokens = new ArrayList<String>();
while(scanner.hasNext()){
tokens.add(scanner.next());
}
String[] words = tokens.toArray(new String[0]); // optional
Also on a side note, it's not necessary to create the JFileChooser
everytime:
class OneButtonListener implements ActionListener
{
private final JFileChooser oneFC = new JFileChooser();
@Override
public void actionPerformed(ActionEvent evt)
{
Upvotes: 1
Reputation: 92056
String contentsOfWholeFile = new Scanner(file).useDelimiter("\\Z").next();
Upvotes: 0
Reputation: 106037
Not having worked with Java in a very long time I may be way off, but it looks like you call inputText = input.nextLine();
exactly once, so it makes sense that you're only getting one line. Presumably you want to call nextLine()
in a loop so that it keeps giving you lines until it gets to the end of the file.
Upvotes: 0