如何让 String Tokenizer 忽略文本?
我有这个代码:
public void readTroops() {
File file = new File("resources/objects/troops.txt");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
StringTokenizer troops = new StringTokenizer(text,"=");
String list = troops.nextToken();
String value = troops.nextToken();
}
和这个文件:
//this is a comment part of the text file//
Total=1
问题是 1)我无法让它忽略 //,// 中的所有内容,并且无法让它通过它们之间的“ENTER”(行)进行读取。例如,此文本有效:
Total=1
所以我的问题是我应该在分隔符区域中输入什么,即。
StringTokenizer troops = new StringTokenizer(text,"=","WHAT GOES HERE?");
那么我怎样才能让 Tokenizer 忽略“ENTER”/新行,以及中间的任何内容 // 或类似的内容,谢谢。
ps.我不在乎你是否使用 String.split 来回答我的问题。
I have this code:
public void readTroops() {
File file = new File("resources/objects/troops.txt");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
StringTokenizer troops = new StringTokenizer(text,"=");
String list = troops.nextToken();
String value = troops.nextToken();
}
and this file:
//this is a comment part of the text file//
Total=1
the problem is that 1) I cant get it to ignore everything within the //,// and can't get it to read with an 'ENTER' (line) in-between them. For example, this text works:
Total=1
So my question is what do I type into the delimiter area ie.
StringTokenizer troops = new StringTokenizer(text,"=","WHAT GOES HERE?");
So how can I get Tokenizer to ignore 'ENTER'/new line, and anything in-between // or something similar, thanks.
ps.I don't care if you use a String.split to answer my question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用方法
countTokens
跳过没有两个标记的行:Use the method
countTokens
to skip lines that don't have two tokens:附:您可以按住并关闭输入流。
ps. you might hold and close input stream.
跳出框框思考,也许您可以使用
Properties
而不是 tokenizer(如果您更新注释以#
开头)?或者,如果您使用的是 Java 7:
Thinking out of the box, maybe you can use
Properties
instead of tokenizer (if you update your comments to start with#
)?Or if you are using Java 7:
如果您正在读取文件,更好的方法是使用 StreamTokenizer。然后,您可以声明自己的标记生成器语法。我用这个方法创建了一个 HTML 渲染引擎。然后,这允许您直接从阅读器解析,并且还提供有用的函数来识别数字,您似乎可能会使用这些函数。
(一旦我的 Eclipse 加载,我将发布一个示例!)
请查看此教程 http: //tutorials.jenkov.com/java-io/streamtokenizer.html
If you are reading in the file a better way would be to use a StreamTokenizer. This then allows you to declare your own syntax of the tokenizer. I used this method to create a HTML rendering engine. This then allows you to parse direct from a reader, and also provides useful functions to identify numbers, which it seems you may use.
(I will post an example once my eclipse loads!)
Check this out for a good tutorial http://tutorials.jenkov.com/java-io/streamtokenizer.html