在文本文件中显示带有行号的搜索文本

时间:2015-03-18 19:34:28

标签: java

所以我一直在研究一个程序,它会显示搜索到的文本字符串的行号和行本身。如果我搜索狗,并且我的文本文件中包含单词dog的行,则应显示这些行和行号。我还创建了一个计算文本文件的字符,单词和行的方法。但是,我遇到的问题是,每当我运行程序时,我都不会使用搜索文本的行来获取行号。我成功地从控制台中的文本文件中获取了文本,并且我成功地获得了行数,单词等。

这是我的书面代码,我猜它必须做一些事实,即我没有"返回结果;"声明,但我不知道在哪里放,如果我把它添加到" +字符+"字符。 ""通过做" +结果",它只是给我空括号。

也许我做错了什么?也许与关闭文件和流有关,不确定。请帮助,我尝试过移动的东西,但没有运气。

public String words() {
    try {
        int words = 0;
        int numbers = 0;
        int lines = 1;
        int characters = 0;
        int total = 0;

        String c = " ";

        FileReader r = new FileReader(file1);
        LineNumberReader lnr = new LineNumberReader(r);
        StreamTokenizer t = new StreamTokenizer(r);
        ArrayList<String> results = new ArrayList<String>();

        t.resetSyntax();
        t.wordChars('0', '9');
        t.wordChars('A', 'Z');
        t.wordChars('a', 'z');
        t.whitespaceChars(0, ' ');

        t.eolIsSignificant(true);

        while (t.nextToken() != StreamTokenizer.TT_EOF) {
            switch (t.ttype) {
                case StreamTokenizer.TT_NUMBER:
                    numbers++;
                    break;
                case StreamTokenizer.TT_WORD:
                    characters += t.sval.length();
                    words++;
                    break;
                case StreamTokenizer.TT_EOL:
                    lines++;
                    break;
                case StreamTokenizer.TT_EOF:
                    break;
                default:

            }
        }

        FileInputStream fstream = new FileInputStream(file1);
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

        String strLine;

        while ((strLine = br.readLine()) != null) {
            System.out.println(strLine);
        }

        br.close();

        String ask = "Enter Word";

        String find = JOptionPane.showInputDialog(ask);
        String word = find;

        String line = null;
        while ((line = lnr.readLine()) != null) {
            if (line.indexOf(word) >= 0) {
                results.add(lnr.getLineNumber() + line);
            }
        }

        r.close();

        total = numbers + words;

        lnr.close();

        return file1.getName() + " has " + lines + " lines, "
                + total + " words, "
                + characters + " characters. ";
    } catch (IOException e) {
        display(e.toString(), "Error");
    }

    return " ";

}

如果需要,这里是主要课程:

import java.io.*;
import java.util.ArrayList;
import javax.swing.*;

public class BasicFile {

File file1;
JFileChooser selection;
File file2 = new File(".", "Backup File");

public BasicFile() {
    selection = new JFileChooser(".");
}

public void selectFile() {
    int status = selection.showOpenDialog(null);

    try {
        if (status != JFileChooser.APPROVE_OPTION) {
            throw new IOException();
        }
        file1 = selection.getSelectedFile();

        if (!file1.exists()) {
            throw new FileNotFoundException();
        }
    } catch (FileNotFoundException e) {
        JOptionPane.showMessageDialog(null, "File Not Found ", "Error", JOptionPane.INFORMATION_MESSAGE);
    } catch (IOException e) {
        System.exit(0);
    }
}

public void backupFile() throws FileNotFoundException {
    DataInputStream in = null;
    DataOutputStream out = null;
    try {
        in = new DataInputStream(new FileInputStream(file1));
        out = new DataOutputStream(new FileOutputStream(file2));

        try {
            while (true) {
                byte data = in.readByte();
                out.writeByte(data);
            }
        } catch (EOFException e) {
            JOptionPane.showMessageDialog(null, "File has been backed up!",
                    "Backup Complete!", JOptionPane.INFORMATION_MESSAGE);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "File Not Found ",
                    "Error", JOptionPane.INFORMATION_MESSAGE);
        }
    } finally {
        try {
            in.close();
            out.close();
        } catch (Exception e) {
            display(e.toString(), "Error");
        }
    }

}

boolean exists() {
    return file1.exists();
}

public String toString() {
    return file1.getName() + "\n" + file1.getAbsolutePath() + "\n" + file1.length() + " bytes";
}

public String words() {
    try {
        int words = 0;
        int numbers = 0;
        int lines = 1;
        int characters = 0;
        int total = 0;

        String c = " ";

        FileReader r = new FileReader(file1);
        LineNumberReader lnr = new LineNumberReader(r);
        StreamTokenizer t = new StreamTokenizer(r);
        ArrayList<String> results = new ArrayList<String>();

        t.resetSyntax();
        t.wordChars('0', '9');
        t.wordChars('A', 'Z');
        t.wordChars('a', 'z');
        t.whitespaceChars(0, ' ');

        t.eolIsSignificant(true);

        while (t.nextToken() != StreamTokenizer.TT_EOF) {
            switch (t.ttype) {
                case StreamTokenizer.TT_NUMBER:
                    numbers++;
                    break;
                case StreamTokenizer.TT_WORD:
                    characters += t.sval.length();
                    words++;
                    break;
                case StreamTokenizer.TT_EOL:
                    lines++;
                    break;
                case StreamTokenizer.TT_EOF:
                    break;
                default:

            }
        }

        FileInputStream fstream = new FileInputStream(file1);
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

        String strLine;

        while ((strLine = br.readLine()) != null) {
            System.out.println(strLine);
        }

        br.close();

        String ask = "Enter Word";

        String find = JOptionPane.showInputDialog(ask);
        String word = find;

        String line = null;
        while ((line = lnr.readLine()) != null) {
            if (line.indexOf(word) >= 0) {
                results.add(lnr.getLineNumber() + line);
            }
        }

        r.close();

        total = numbers + words;

        lnr.close();

        return file1.getName() + " has " + lines + " lines, "
                + total + " words, "
                + characters + " characters. ";
    } catch (IOException e) {
        display(e.toString(), "Error");
    }

    return " ";

}

void display(String msg, String s) {
    JOptionPane.showMessageDialog(null, msg, s, JOptionPane.ERROR_MESSAGE);
}

}

2 个答案:

答案 0 :(得分:0)

你可以做的是开始计算文件中的行starting by 0),然后每次找到新行时increase by 1 ..然后检查您要查找的字符串是否包含在行中,然后print the number of the line where the keyword is found(使用Java中的contains()函数)。我假设您要检查大写和小写,如果您不想要,那么只需删除toLowerCase()!因此,在Java中正确读取文件:

        long lineNumber = 0;
        BufferedReader myReader = new BufferedReader(new FileReader("test.txt")); 
        String line = myReader.readLine();
            while(line != null){
                lineNumber++;
                System.out.println("The line I am now examining is : " + line + " and the line number is : " + lineNumber);
                if line.toLowerCase().contains(word.toLowerCase()) {
                System.out.println("Line number: " + lineNumber + " contains keyword : " + word);
                line = myReader.readLine();
            } 

答案 1 :(得分:0)

你快到了。

while ((line = lnr.readLine()) != null)循环之前重新初始化FileReader和LineNumberReader。

然后你的ArrayList将充满我认为你想要的#String。