如何让 String Tokenizer 忽略文本?

发布于 2024-12-27 03:28:49 字数 1010 浏览 6 评论 0原文

我有这个代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

如果没结果 2025-01-03 03:28:49

使用方法 countTokens 跳过没有两个标记的行:

while ((text = reader.readLine()) != null) { 
        StringTokenizer troops = new StringTokenizer(text,"="); 
        if(troops.countTokens() == 2){
            String list = troops.nextToken(); 
            String value = troops.nextToken(); 
            ....
        }else { 
            //ignore this line
        }
} 

Use the method countTokens to skip lines that don't have two tokens:

while ((text = reader.readLine()) != null) { 
        StringTokenizer troops = new StringTokenizer(text,"="); 
        if(troops.countTokens() == 2){
            String list = troops.nextToken(); 
            String value = troops.nextToken(); 
            ....
        }else { 
            //ignore this line
        }
} 
空城缀染半城烟沙 2025-01-03 03:28:49
Properties prop = new Properties();
prop.load(new FileInputStream("properties_file.txt"));
assertExuals("1",prop.getProperty("Total"));

附:您可以按住并关闭输入流。

Properties prop = new Properties();
prop.load(new FileInputStream("properties_file.txt"));
assertExuals("1",prop.getProperty("Total"));

ps. you might hold and close input stream.

晒暮凉 2025-01-03 03:28:49

跳出框框思考,也许您可​​以使用 Properties 而不是 tokenizer(如果您更新注释以 # 开头)?

Properties troops = new Properties();
InputStream inputStream = SomeClass.class.getResourceAsStream("troops.properties");
try {
    props.load(inputStream);
} catch (IOException e) {
    // Handle error
} finally {
    // Close inputStream in a safe manner
}
troops.getProperty("Total"); // Returns "1"

或者,如果您使用的是 Java 7:

Properties troops = new Properties();
try (InputStream inputStream = SomeClass.class.getResourceAsStream("troops.properties")) {
    props.load(inputStream);
} catch (IOException e) {
    // Handle error
}
troops.getProperty("Total"); // Returns "1"

Thinking out of the box, maybe you can use Properties instead of tokenizer (if you update your comments to start with #)?

Properties troops = new Properties();
InputStream inputStream = SomeClass.class.getResourceAsStream("troops.properties");
try {
    props.load(inputStream);
} catch (IOException e) {
    // Handle error
} finally {
    // Close inputStream in a safe manner
}
troops.getProperty("Total"); // Returns "1"

Or if you are using Java 7:

Properties troops = new Properties();
try (InputStream inputStream = SomeClass.class.getResourceAsStream("troops.properties")) {
    props.load(inputStream);
} catch (IOException e) {
    // Handle error
}
troops.getProperty("Total"); // Returns "1"
疧_╮線 2025-01-03 03:28:49

如果您正在读取文件,更好的方法是使用 StreamTokenizer。然后,您可以声明自己的标记生成器语法。我用这个方法创建了一个 HTML 渲染引擎。然后,这允许您直接从阅读器解析,并且还提供有用的函数来识别数字,您似乎可能会使用这些函数。
(一旦我的 Eclipse 加载,我将发布一个示例!)

public static String render(String file, HashMap vars){

    // Create a stringbuffer to rebuild the string
    StringBuffer renderedFile = new StringBuffer();
    try{
    FileReader in = new FileReader(file); 
     BufferedReader reader = new BufferedReader(in); // create your reader
    StreamTokenizer tok;
        tok = new StreamTokenizer(reader); //the tokenizer then takes in the reader as a builder
        tok.resetSyntax();
        tok.wordChars(0, 255); //sets all chars (inc spaces to be counted as words)
        /*
         *  quoteChar allows you to set your comment char, for example $ hello $ means it will ignore hello 
         */
        tok.quoteChar('

请查看此教程 http: //tutorials.jenkov.com/java-io/streamtokenizer.html

); while(tok.nextToken()!=StreamTokenizer.TT_EOF){ //while it is not at the end of file String s = tok.sval; if (vars.containsKey(s)) s =(String)vars.get(s); renderedFile.append(s); } } catch(Exception e){System.out.println("Error Loading Template");} return renderedFile.toString(); }

请查看此教程 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!)

public static String render(String file, HashMap vars){

    // Create a stringbuffer to rebuild the string
    StringBuffer renderedFile = new StringBuffer();
    try{
    FileReader in = new FileReader(file); 
     BufferedReader reader = new BufferedReader(in); // create your reader
    StreamTokenizer tok;
        tok = new StreamTokenizer(reader); //the tokenizer then takes in the reader as a builder
        tok.resetSyntax();
        tok.wordChars(0, 255); //sets all chars (inc spaces to be counted as words)
        /*
         *  quoteChar allows you to set your comment char, for example $ hello $ means it will ignore hello 
         */
        tok.quoteChar('

Check this out for a good tutorial http://tutorials.jenkov.com/java-io/streamtokenizer.html

); while(tok.nextToken()!=StreamTokenizer.TT_EOF){ //while it is not at the end of file String s = tok.sval; if (vars.containsKey(s)) s =(String)vars.get(s); renderedFile.append(s); } } catch(Exception e){System.out.println("Error Loading Template");} return renderedFile.toString(); }

Check this out for a good tutorial http://tutorials.jenkov.com/java-io/streamtokenizer.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文