如何用Java中的Scanner类解决行尾读取问题

发布于 2024-08-29 05:56:14 字数 1550 浏览 5 评论 0原文

我不是一位经验丰富的 Java 程序员,我正在尝试将一些文本写入文件,然后使用 Scanner 读取它。我知道有很多方法可以做到这一点,但我想将记录写入带有分隔符的文件,然后读取这些片段。

问题这么小。当我查看输出时,没有看到一些打印(如下所示)。我的意思是输出中仅写有“扫描仪”的粗线。如果有人能回答为什么没有看到“String:”,我将不胜感激。 (请回答我的问题)

我不明白这是一个简单的打印问题还是“\r\n”的行结束问题。

这是代码:


    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Scanner;

public class Tmp {
    public static void main(String args[]) throws IOException {
        int i;
        boolean b;
        String str;

        FileWriter fout = new FileWriter("test.txt");
        fout.write("Testing|10|true|two|false\r\n");
        fout.write("Scanner|12|one|true|");
        fout.close();

        FileReader fin = new FileReader("Test.txt");

        Scanner src = new Scanner(fin).useDelimiter("[|\\*]");

        while (src.hasNext()) {
            if (src.hasNextInt()) {
                i = src.nextInt();
                System.out.println("int: " + i);
            } else if (src.hasNextBoolean()) {
                b = src.nextBoolean();
                System.out.println("boolean: " + b);
            } else {
                str = src.next();
                System.out.println("String: " + str);
            }
        }

        fin.close();
    }
}   

这是输出:


String: Testing
int: 10
boolean: true
String: two
String: false
Scanner
int: 12
String: one
boolean: true

I am not an experienced Java programmer and i'm trying to write some text to a file and then read it with Scanner. I know there are lots of ways of doing this, but i want to write records to file with delimiters, then read the pieces.

The problem is so small. When I look the output some printing isn't seen(shown in below). I mean the bold line in the Output that is only written "Scanner". I would be appreciated if anyone can answer why "String: " isn't seen there. (Please answer just what i ask)

I couldn't understand if it is a simple printing problem or a line end problem with "\r\n".

Here is the code:


    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Scanner;

public class Tmp {
    public static void main(String args[]) throws IOException {
        int i;
        boolean b;
        String str;

        FileWriter fout = new FileWriter("test.txt");
        fout.write("Testing|10|true|two|false\r\n");
        fout.write("Scanner|12|one|true|");
        fout.close();

        FileReader fin = new FileReader("Test.txt");

        Scanner src = new Scanner(fin).useDelimiter("[|\\*]");

        while (src.hasNext()) {
            if (src.hasNextInt()) {
                i = src.nextInt();
                System.out.println("int: " + i);
            } else if (src.hasNextBoolean()) {
                b = src.nextBoolean();
                System.out.println("boolean: " + b);
            } else {
                str = src.next();
                System.out.println("String: " + str);
            }
        }

        fin.close();
    }
}   

Here is the output:


String: Testing
int: 10
boolean: true
String: two
String: false
Scanner
int: 12
String: one
boolean: true

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

也只是曾经 2024-09-05 05:56:14

您没有正确设置分隔符; [|\\*] 是由 2 个字符 |* 组成的字符类。

    String s = "hello|world*foo*bar\r\nEUREKA!";
    System.out.println(s);
    // prints:
    // hello|world*foo*bar
    // EUREKA!

    Scanner sc;

    sc = new Scanner(s).useDelimiter("[|\\*]");
    while (sc.hasNext()) {
        System.out.print("[" + sc.next() + "]");
    }
    // prints:
    // [hello][world][foo][bar
    // EUREKA!]

    System.out.println();

    sc = new Scanner(s).useDelimiter("\r?\n|\r|\\|");
    while (sc.hasNext()) {
        System.out.print("[" + sc.next() + "]");
    }
    // prints:
    // [hello][world*foo*bar][EUREKA!]      

您似乎发现 "[|\\n]" “有效”,但这实际上在某些标记的末尾留下了尾随 \r

巧合的是,您应该查找 PrintWriter;它具有使用系统属性line.separatorprintln 方法。它基本上就是System.out 的本质。

PrintWriter fout = new PrintWriter(new File("test.txt"));
fout.println("Testing|10|true|two|false");

You're not setting your delimiter right; [|\\*] is a character class consisting of 2 characters, |, *.

    String s = "hello|world*foo*bar\r\nEUREKA!";
    System.out.println(s);
    // prints:
    // hello|world*foo*bar
    // EUREKA!

    Scanner sc;

    sc = new Scanner(s).useDelimiter("[|\\*]");
    while (sc.hasNext()) {
        System.out.print("[" + sc.next() + "]");
    }
    // prints:
    // [hello][world][foo][bar
    // EUREKA!]

    System.out.println();

    sc = new Scanner(s).useDelimiter("\r?\n|\r|\\|");
    while (sc.hasNext()) {
        System.out.print("[" + sc.next() + "]");
    }
    // prints:
    // [hello][world*foo*bar][EUREKA!]      

You seemed to have found that "[|\\n]" "works", but this actually leaves a trailing \r at the end of some tokens.

Coincidentally, you should look up PrintWriter; it has println methods that uses the system property line.separator. It's basically what System.out is-a.

PrintWriter fout = new PrintWriter(new File("test.txt"));
fout.println("Testing|10|true|two|false");
_畞蕅 2024-09-05 05:56:14

问题是您正在写出字符串“String:”,然后写出控制字符 \r 或回车符,然后写出内容。

以下版本应该更适合您:

FileWriter fout = new FileWriter("test.txt");
fout.write("Testing|10|true|two|false\n");
fout.write("Scanner|12|one|true|");
fout.close();
FileReader fin = new FileReader("test.txt");
Scanner src = new Scanner(fin).useDelimiter("[|\n]");

要真正了解我正在谈论的 \r,您应该更改原始程序,以便打印代码如下所示:

  } else {
    str = src.next().trim();
    str = str.replace('\n', '_');
    str = str.replace('\r', '_');
    System.out.println("String: " + str);
  }

您应该看到输出:

字符串: false__Scanner

The problem is that you are writing out the String "String: " and then writing out control character \r, or carriage return, and then writing out the contents.

The following version should work a bit better for you:

FileWriter fout = new FileWriter("test.txt");
fout.write("Testing|10|true|two|false\n");
fout.write("Scanner|12|one|true|");
fout.close();
FileReader fin = new FileReader("test.txt");
Scanner src = new Scanner(fin).useDelimiter("[|\n]");

To really see what I am talking about with the \r, you should change your original program so the print code looks like this:

  } else {
    str = src.next().trim();
    str = str.replace('\n', '_');
    str = str.replace('\r', '_');
    System.out.println("String: " + str);
  }

You should see the output:

String: false__Scanner

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