Bufferedreader读取某些行和文本

时间:2015-03-18 21:15:34

标签: java bufferedreader string-split file-read

这是我的第一篇文章,所以我不确定这里的工作方式。 基本上,我需要一些帮助/建议与我的代码。该方法需要读取某一行并在输入的文本后打印出文本并且=

文本文件需要

A = Ant

B = Bird

C = Cat

因此,如果用户输入"A",则应打印出类似

的内容
-Ant

到目前为止,我设法忽略"=",但仍然打印出整个文件

这是我的代码:

public static void readFromFile() {
    System.out.println("Type in your word");
    Scanner scanner = new Scanner(System.in);
    String input = scanner.next();
    String output = "";
    try {
        FileReader fr = new FileReader("dictionary.txt");           
        BufferedReader br = new BufferedReader(fr);            
        String[] fields;
        String temp;
        while((input = br.readLine()) != null) {
            temp = input.trim();
            if (temp.startsWith(input)) {
                String[] splitted = temp.split("=");
                output += splitted[1] + "\n";
            }
        }
        System.out.print("-"+output);
    }
    catch(IOException e) {

    }
}

4 个答案:

答案 0 :(得分:2)

看起来这条线是问题所在,因为它始终是真的。

if (temp.startsWith(input))

您需要为从文件中读取的行以及您从用户保留的输入使用不同的变量。尝试类似:

String fileLine;
while((fileLine = br.readLine()) != null)
    {
        temp = fileLine.trim();
        if (temp.startsWith(input))
        {
            String[] splitted = temp.split("=");
            output += splitted[1] + "\n";
        }
    }

答案 1 :(得分:0)

试试这个,它有效:步骤:

1)使用input阅读scanner 2)使用file阅读bufferedreader 3)使用split作为"-"的每一行delimiter 4)compare first line字符input 5)if first character等于input然后print the associated valuepreceded by a "-"

import java.io.BufferedReader; 
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.util.Scanner; 
class myRead{
    public static void main(String[] args) throws FileNotFoundException, IOException {
        System.out.println("Type in your word");
        Scanner scanner = new Scanner(System.in);
        String input = scanner.next();
        long numberOfLines = 0;
        BufferedReader myReader = new BufferedReader(new FileReader("test.txt")); 
        String line = myReader.readLine();
            while(line != null){
                String[] parts = line.split("=");
                if (parts[0].trim().equals(input.trim())) {
                System.out.println("-"+parts[1]);
                }
                line = myReader.readLine();
            } 
}
}

输出(取决于输入):

- Ant
- Bird
- Cat

答案 2 :(得分:0)

您可以使用useDelimiter()的{​​{1}}方法来分割输入文字

Scanner

以下代码是我在IDEONE(http://ideone.com/TBwCFj

中尝试过的
scanner.useDelimiter("(.)*="); // Matches 0 or more characters followed by '=', and then gives you what is after `=`

答案 3 :(得分:0)

您需要先按新行分割文本文件" \ n" (假设在每个" A = Ant"," B = Bird"," C = Cat"声明它以新行开头)然后找到输入的字符进一步分裂为" ="就像你在做的那样。

因此,您需要两个字符串数组(String []),每行一个,另一个用于将每行分隔成例如1行。 " A"和" Ant"。 你非常接近。

相关问题