扫描仪只读取文件名而不读取其他内容 [英] Scanner only reads file name and nothing else
问题描述
我正在尝试实现一个基本的词法分析器.我现在被困在文件解析上.
I'm trying to implement a rudimentary lexer. I'm stuck on the file parsing at the moment.
public ArrayList<Token> ParseFile () {
int lineIndex = 0;
Scanner scanner = new Scanner(this.fileName);
while (scanner.hasNextLine()) {
lineIndex++;
String line = scanner.nextLine();
if (line.equals(""))
continue;
String[] split = line.split("\s");
for (String s : split) {
if (s.equals("") || s.equals("\s*") || s.equals(" "))
continue;
Token token = new Token(s, lineIndex);
parsedFile.add(token);
}
}
scanner.close();
return this.parsedFile;
}
这是我的文件,叫做p++.ppp"
This is my fille called "p++.ppp"
#include<iostream>
using namespace std ;
int a ;
int b ;
int main ( ) {
cin >> a ;
cin >> b ;
while ( a != b ) {
if ( a > b )
a = a - b ;
if ( b > a )
b = b - a ;
}
cout << b ;
return 0 ;
}
当我解析文件时,我得到:Error, token: p++.ppp on line: 1 is not valid
但 p++.ppp 是文件名!
When I parse the file, I get: Error, token: p++.ppp on line: 1 is not valid
but p++.ppp is the file name!
此外,当我调试时,它会读取文件名,然后在 scanner.hasNextLine()
处退出.我错过了什么?
Also when I debug, it reads the file name and then at scanner.hasNextLine()
it just exits. What am I missing ?
推荐答案
您误解了 Scanner
的 API.来自 Scanner(String)
构造函数:
You've misunderstood the API for Scanner
. From the docs for the Scanner(String)
constructor:
构造一个新的 Scanner,生成从指定字符串扫描的值.
Constructs a new Scanner that produces values scanned from the specified string.
参数:
源 - 要扫描的字符串
Parameters:
source - A string to scan
它不是文件名 - 它只是一个字符串.
It's not a filename - it's just a string.
您应该改用 Scanner(File)
构造函数 - 或者更好的是,也使用 Scanner(File, String)
构造函数来指定编码.例如:
You should use the Scanner(File)
constructor instead - or better yet, the Scanner(File, String)
constructor to specify the encoding as well. For example:
try (Scanner scanner = new Scanner(new File(this.fileName), "UTF_8")) {
...
}
(注意使用 try-with-resources 语句,以便扫描器自动关闭.)
(Note the use of a try-with-resources statement so the scanner gets closed automatically.)
这篇关于扫描仪只读取文件名而不读取其他内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!