简体   繁体   English

Java:扫描仪无法扫描整行

[英]Java: scanner not scanning complete lines

I have the following text file (not a java file) 我有以下文本文件(不是Java文件)

/*START OF CHANGES TO CODE*/
public class method1 {

    public static int addTwoNumbers(int one, int two){
        return one+two;
    }

    public static void main (String[] args){
        int total = addTwoNumbers(1, 3);
        System.out.println(total);
    }
}
/*END OF CHANGES TO CODE*/

I am trying to use the following code to read the file 我正在尝试使用以下代码读取文件

String editedSection = null;
boolean containSection = false;
Scanner in = new Scanner(new FileReader(directoryToAddFile));
while(in.hasNextLine()) {
    if(in.nextLine().contains("/*START OF CHANGES TO CODE*/")) {
        containSection = true;
        editedSection = in.nextLine().toString();
    } else if (containSection == true) {
        editedSection = editedSection+in.nextLine().toString();
    } else if (in.nextLine().contains("/*END OF CHANGES TO CODE*/")) {
        containSection = false;
        editedSection = in.nextLine().toString();
    }
    in.nextLine();
}

So basically what i want it to do is read a file till it see's /*START OF CHANGES TO CODE*/ , then start adding every line after this to a string till it reaches /*END OD CHANGES TO CODE*/ . 因此,基本上,我要它执行的操作是读取一个文件,直到看到/*START OF CHANGES TO CODE*/ ,然后在此之后将每一行添加到字符串中,直到达到/*END OD CHANGES TO CODE*/ But when it is reading lines it ignores some lines and parts of others. 但是,当它在阅读线条时,会忽略某些线条和其他线条。 Does anyone know how to do this? 有谁知道如何做到这一点?

You're calling in.nextLine() lots of times within that while loop. 你打电话in.nextLine() 很多那个时代内while循环。 That sounds like a really bad idea to me. 对我来说,这听起来真是个坏主意。 How many times it will execute on each iteration will depend on which bits it went into... nasty. 它在每次迭代中执行多少次将取决于它进入了哪些位。

I suggest you use 我建议你用

while(in.hasNextLine()) {
    String line = in.nextLine();
    // Now use line for the whole of the loop body
}

That way you won't accidentally skip lines by reading them just for checking purposes. 这样一来,您不会因阅读而仅出于检查目的而意外跳过行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM