如何阅读某一行&在Java之后的几行

时间:2017-06-23 17:37:12

标签: java

编辑:好的,所以我想找到一个特定的行,然后在找到的行之后打印几行(4)。这就是我现在所拥有的,但是遇到了很多错误(大多数没有建立FileNotFoundException,但是它在那里我不知道最近会发生什么)以及一个错误说我需要一个;在'for'循环中。请帮忙吗?

monkey - jean
detail 1
detail 2
detail 3
detail 4

marmaset - rick
detail 1
detail 2
detail 3
*****detail 4

示例源文件:

marmaset - rick
detail 1
detail 2
detail 3
ALERT: detail 4
如果用户输入是marmaset,则

和预期输出:

<<relimpsum, echo=-c(1,3,4,5)>>=
## load relimp package
library(relimp)
## calculate relative improtance of
## sector (coefs 3:11) and
## nation (coefs 12:14)
relimp(mod1, set1=3:11, set2=12:14)
@

1 个答案:

答案 0 :(得分:-1)

看看这对你有用......

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

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

这是Animal类,其中包含您尝试创建的方法(我认为)。

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