开发者

Manipulating strings from a file

开发者 https://www.devze.com 2023-03-18 05:48 出处:网络
I have a file with a syntax that looks like this: ! <Group>, Column1, column2, column3 Group, 10, 20, 30

I have a file with a syntax that looks like this:

! <Group>, Column1, column2, column3 
Group, 10, 20, 30
Group, 11, 12, 13
...
! <AnotherGroup>, Column1, column2, column3, column4
AnotherGroup, 10, 20, 30, A
AnotherGroup, 11, 12, 13, B
...

When I try to manipulate the strings through the Scanner object, some strange things are happening such as:

  • end of file is found
  • sometimes does not recognize the character "!" (see code snippet)
  • sometimes does not recognize space characters

        sc = new Scanner(new File("files/myFile"));
    while (sc.hasNextLine()) {
        String tempLine = sc.nextLine();
        if (tempLine.contains("!")) {
            System.out.println(tempLine);
    

Anyway, I think I have to read the entire file and stores it in a specific format in order to manipulate.

开发者_开发百科

Any advices?

Edited after first answer: This is the case wich sometimes does not recognize the character "!" (see code snippet)

My Sysout:

! <Group1>, Column1, column2, column3 
! <Group2>, Column1, column2, column3 
! <Group5>, Column1, column2, column3

Didnt read the lines with groups 3 and 4


I dont think that there is a problem with the Scanner. At least the part of the code that you have provided should work fine. May be verify if you are doing some silly mistake or wait until some gurus come to your help ;-)


I think you are misunderstanding how the scanner works. nextLine() causes the scanner to skip over the rest of the current line it is looking at, and it returns a String containing the text that was skipped. It leaves the scanner at the beginning of the next line.

You did not explain the context of when your strange things happen. When you say "end of file is found" is one of your strange things that is happening, I will assume this happens near the end when you would expect one more line to be processed. If the scanner is looking at the beginning of the last line in the file, what is hasNextLine() going to return? Your while loop is going to be finished without processing some of your file's contents. If this is not the behavior you are experiencing, you need to explain better.

If you want to use a scanner, try checking out something like this.

0

精彩评论

暂无评论...
验证码 换一张
取 消