如何在Java中阅读某一行&后面几行

如何在Java中阅读某一行&后面几行,java,Java,编辑:好的,我正在寻找一个特定的行,然后在找到的行之后打印几行。这就是我现在所拥有的,但是得到了很多错误,大多数都没有建立FileNotFoundException,但是它在那里,所以我不知道发生了什么,一个错误说我需要一个;在“for”循环中。请帮忙 import java.io.BufferedReader; import java.io.FileReader; import java.io.FileNotFoundException; public class Animals { St

编辑:好的,我正在寻找一个特定的行,然后在找到的行之后打印几行。这就是我现在所拥有的,但是得到了很多错误,大多数都没有建立FileNotFoundException,但是它在那里,所以我不知道发生了什么,一个错误说我需要一个;在“for”循环中。请帮忙

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;

public class Animals {

String line;
int i = 0;

BufferedReader animals = new BufferedReader(new FileReader 
    ("‪//Documents//animals.txt"));

string animalChoices () {
    string animalChoice = while ((line = animals.readLine()) != null)) {
        for (i = 0, i < 4, i++) {
         System.out.print(line);
    }
}
}

string displayAnimals () {
  string displayAnimal = while ((line = animals.readLine()) != null) {
        for (i=0, i<4, i++) {
            if (line.contains("*****")) {
                string alertLine = line.replace("*****", "ALERT!!! ");
                system.out.println(alertLine);
            }
            else if {
                system.out.println(line);
            }
        }
    }
}
}
如果用户输入为marmaset,则为预期输出:

marmaset - rick
detail 1
detail 2
detail 3
ALERT: detail 4

看看这是否适合你

我创建了一个包含以下内容的文件:

This is a line 123
This is a line 456
This is a line 789
This is a line 012

This is a line 345

This is a line 678

This is a line 901

This is a line 234
This is a line 567
以下是我如何使用您的条件进行搜索:

package stackoverflow;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class CustomFileReader {

/**
 * Grab a line from a file containing a pattern, and a number of "non-zero"
 * lines after it.  Return array of Strings as the result. 
 * @param file File to search
 * @param containsThis text string first line must have...
 * @param linesToGrab # of lines to grab total.
 * @return null if file doesn't exist or the string pattern wasn't found.
 */
public static String[] getLines(File file, String containsThis,int linesToGrab)
{
    if(!file.exists()){
        System.err.println("File doesn't exist...");
        return null;
    }

    int linesGrabbed = 0;
    String[] result = new String[linesToGrab];
    boolean lookingForPattern = true;
    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        for(String line; (line = br.readLine()) != null; )
        {
            if(lookingForPattern){
                if(line.contains(containsThis)){
                    result[linesGrabbed++] = line;
                    lookingForPattern = false;
                }
            }
            else{
                /** Got the pattern, now just grab lines that are "non-zero". */
                if(line.length() > 0){
                    result[linesGrabbed++] = line;
                    if(linesGrabbed >= linesToGrab){ 
                        br.close();
                        return result; 
                    }
                }
            }
        }
    } catch (Exception e) {
        System.err.println(e.toString());
    }
    return result;
    }
}
下面是我如何使用它

public static void main(String[] args) {
    String[] result = CustomFileReader.getLines(
            new File("c:/stackoverflow/myFile.txt"), "012", 5);

    if(result != null){
        for(String line : result){
            System.out.println(line);
        }
    }
}
这是我得到的结果

This is a line 012
This is a line 345
This is a line 678
This is a line 901
This is a line 234
为了让我的答案更像你的代码所追求的,这里是另一个你可以尝试的版本

我创建了另一个包含动物的文件:

Some random line
Another ramdom line
*****
lion
tiger

bear
cow

pig
chicken
panda
这是一个动物类,里面有我认为你试图创建的方法

package stackoverflow;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

public class Animals 
{

    /**
     * Based on your code, I'm guessing this method is meant to read all 
     * lines of a file containing a list of animals and return all the lines 
     * read from the file to whoever called this method...
     * I used a List instead of an array since you don't have to know how 
     * many lines are in the file ahead of time (you'd need to initialize an 
     * array, not a List.) I'll demonstrate how to access the List of 
     * Strings in the example.
     * @param filename pathname of the file. Ex. "c:/stackoverflow/myFile.txt"
     * or "c:\\stackoverflow\\myFile.txt"
     * @return List of Strings read from the file.
     */
    public static List<String> animalChoices (String filename) 
    {
        List<String> animalChoiceList = new ArrayList<>();

        BufferedReader animals;
        try {
            animals = new BufferedReader(new FileReader(filename));
        } catch (FileNotFoundException ex) {
            System.err.println(ex.toString());
            /* list returned with no entries. */
            return animalChoiceList;
        }

        try {
            String line;
            while ((line = animals.readLine()) != null) 
            {
                animalChoiceList.add(line);
            } 
            animals.close();
        } catch (Exception e) {
            System.err.println(e.toString());
        }
        return animalChoiceList;
    }

    /**
     * Search a provided filename for a certain character string, add that
     * line to a String array, replace it with "ALERT!!! ", then add the
     * next (linesToGrab - 1) lines and add those to the array. Skip 
     * blank lines.
     * @param filename file path in String format "c:/folder/filename.txt"
     * @param searchCriteria ex. "*****" or "lion" or "1234"
     * @param linesToGrab total number of lines to grab
     * @return String array with the results. null if file not there.
     */
    public static String[] displayAnimals(String filename, 
            String searchCriteria, int linesToGrab)
    {
        /* initialize the array to linesToGet long. */
        String[] result = new String[linesToGrab];

        BufferedReader animals;
        try {
            animals = new BufferedReader(new FileReader(filename));
        } catch (FileNotFoundException ex) {
            System.err.println(ex.toString());
            /* return null if a reader could not be opened */
            return null;
        }

        int linesGrabbed = 0;
        boolean lookingForPattern = true;
        try {
            for(String line; (line = animals.readLine()) != null; )
            {
                if(lookingForPattern){
                    if(line.contains(searchCriteria)){
                        result[linesGrabbed++] = 
                                line.replace(searchCriteria, "ALERT!!! ");
                        lookingForPattern = false;
                    }
                }
                else{
                    /** Got the pattern, now just grab lines that are "non-zero". */
                    if(line.length() > 0){
                        result[linesGrabbed++] = line;
                        if(linesGrabbed >= linesToGrab){ 
                            animals.close();
                            return result; 
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.err.println(e.toString());
        }
        return result;
    }
}

你们已经学会如何使用扫描器了吗?是的,这次我附加了一些代码。为什么所有的东西都是小写的?你知道的。Java区分大小写,2。Java类都以大写字母开头,例如String、System。3.字符串displayAnimal=while。。。这是错误的。请看一下如何进行正确的变量赋值和循环。更好。但对于文件路径,请始终使用绝对路径文件路径来驱动字母,直到其他所有操作都正常为止。相对路径从正在运行的.class文件开始。您应该只使用单斜杠。你可能想逃避他们,但那是用反斜杠完成的\\。您的正确路径应该类似于C:/Users//Documents/animals.txt是否有一种基于用户输入运行此操作的方法?例如,如果我们想在您的案例中查找数字,它的运行方式与您所展示的相同,或者如果我们想查找字母,那么假设所发布的数字是字母的各个字母,而数字是以字符串的形式呈现的,因此,您可以用e 0替换012,它会找到相同的行。关于最初尝试中的一些语法,我建议您尝试使用诸如NetBeans IDE之类的程序。您的错误将以红色突出显示,指出您需要更改的内容,例如字符串条目。因此,对于每只动物,都有一个四行的列表,下面有详细信息。这是统一的,我将编辑问题以更好地显示它。抱歉。我一直很好奇,是否有可能在选定的一行之后阅读n行。******用于应显示的警报。
package stackoverflow;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

public class Animals 
{

    /**
     * Based on your code, I'm guessing this method is meant to read all 
     * lines of a file containing a list of animals and return all the lines 
     * read from the file to whoever called this method...
     * I used a List instead of an array since you don't have to know how 
     * many lines are in the file ahead of time (you'd need to initialize an 
     * array, not a List.) I'll demonstrate how to access the List of 
     * Strings in the example.
     * @param filename pathname of the file. Ex. "c:/stackoverflow/myFile.txt"
     * or "c:\\stackoverflow\\myFile.txt"
     * @return List of Strings read from the file.
     */
    public static List<String> animalChoices (String filename) 
    {
        List<String> animalChoiceList = new ArrayList<>();

        BufferedReader animals;
        try {
            animals = new BufferedReader(new FileReader(filename));
        } catch (FileNotFoundException ex) {
            System.err.println(ex.toString());
            /* list returned with no entries. */
            return animalChoiceList;
        }

        try {
            String line;
            while ((line = animals.readLine()) != null) 
            {
                animalChoiceList.add(line);
            } 
            animals.close();
        } catch (Exception e) {
            System.err.println(e.toString());
        }
        return animalChoiceList;
    }

    /**
     * Search a provided filename for a certain character string, add that
     * line to a String array, replace it with "ALERT!!! ", then add the
     * next (linesToGrab - 1) lines and add those to the array. Skip 
     * blank lines.
     * @param filename file path in String format "c:/folder/filename.txt"
     * @param searchCriteria ex. "*****" or "lion" or "1234"
     * @param linesToGrab total number of lines to grab
     * @return String array with the results. null if file not there.
     */
    public static String[] displayAnimals(String filename, 
            String searchCriteria, int linesToGrab)
    {
        /* initialize the array to linesToGet long. */
        String[] result = new String[linesToGrab];

        BufferedReader animals;
        try {
            animals = new BufferedReader(new FileReader(filename));
        } catch (FileNotFoundException ex) {
            System.err.println(ex.toString());
            /* return null if a reader could not be opened */
            return null;
        }

        int linesGrabbed = 0;
        boolean lookingForPattern = true;
        try {
            for(String line; (line = animals.readLine()) != null; )
            {
                if(lookingForPattern){
                    if(line.contains(searchCriteria)){
                        result[linesGrabbed++] = 
                                line.replace(searchCriteria, "ALERT!!! ");
                        lookingForPattern = false;
                    }
                }
                else{
                    /** Got the pattern, now just grab lines that are "non-zero". */
                    if(line.length() > 0){
                        result[linesGrabbed++] = line;
                        if(linesGrabbed >= linesToGrab){ 
                            animals.close();
                            return result; 
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.err.println(e.toString());
        }
        return result;
    }
}
package stackoverflow;

import java.util.List;

public class StackOverflow {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        String filename = "c:/stackoverflow/animalFile.txt";

        List<String> animals = Animals.animalChoices(filename);
        System.out.println("All lines in the file:");
        for(String animal : animals){
            System.out.println(animal);
        }

        int linesToGet = 5;
        String searchCriteria = "*****";
        String[] result = 
                Animals.displayAnimals(filename, searchCriteria, linesToGet);
        System.out.println("\n\nOnly lines after the search criteria");
        for(String line : result){
            System.out.println(line);
        }
    }

}
All lines in the file:
Some random line
Another ramdom line
*****
lion
tiger

bear
cow

pig
chicken
panda


Only lines after the search criteria
ALERT!!! 
lion
tiger
bear
cow