搜索单词

时间:2016-04-17 12:13:21

标签: bufferedreader bluej

这是我在txt文件中搜索特定单词的代码,但是如果我正在搜索的单词在第一行显示,则表示已找到该单词,但如果该单词位于除第1行以外的其他行,则可以找不到它。还有一件事我想在BufferedReader或FileReader中实现它。

 public void searchfile(String word)
      {
       try {

         BufferedReader bf = new BufferedReader(new FileReader("E:\\Books\\OOP\\dictionary\\Dictionary.txt"));
          int linecount = 0;
           String line;


        System.out.println("Searching for " + word + " in file...\n\n");
        while (( line = bf.readLine()) != null)
        {
                 linecount++;




                int indexfound = line.indexOf(word);



                if (line.equals(word)) {

                     System.out.println("Word you are searching for, was found in your file at position " +indexfound+" and line "+linecount);

                }
                else{
                    FileWriter fw = new FileWriter("Dictionary.txt",true);

                       BufferedWriter bw = new BufferedWriter(fw);
                       bw.write("\n");
                           bw.write(word);

                            bw.close();
                       System.out.print("Word was not found\n\n\nYour word has been added to your file");

                           }

                 bf.close();


                         }

           }
         catch (IOException e) {





                       }

           }

1 个答案:

答案 0 :(得分:0)

如果每行都有一个单词,您只需将每个单词加载到List<String>对象上,然后检查每个单词是否都是您的单词。例如:

如果每个单词之间有空格,可以将文件的内容加载到byte[],然后使用new String(byte[])构造函数,按空格分割字符串,然后在数组中搜索单词。如果将其他内容拆分,您还可以使用此方法,例如结肠。

如果只有一行,我建议使用BufferedReader,因为它可以快速读取单行,而不是使用String列表或数组。

在您以上述任何方式获得单词后,您可以通过获取列表,数组或字符串中的每个单词并使用equalsequalsIgnoreCase来搜索单词。或contains方法。

我写了一个符合你想要的课程:

package Testers;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.FileReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class FileReading {

    /**
     * Uses a BufferedReader object
     * Reads a line of a file
     * @param file the file to read
     * @return line the line that is read
     * @throws IOException if the file cannot be found, cannot be read or the input stream cannot be closed
     */
    public String readLine(File file) throws IOException{
        String line = "";
        BufferedReader reader = new BufferedReader(new FileReader(file));
        line = reader.readLine();
        reader.close();
        return line;
    }
    /**
     * Uses static methods in the Files class of NIO
     * Reads everything in a file, and puts it in a String
     * @param file the file to read
     * @return a String representing the contents of the file
     * @throws IOException "if an I/O error occurs reading from the stream" (Files.readAllBytes javadoc)
     */
    public String readFileContents(File file) throws IOException {
        String filecontents = "";
        filecontents = new String(Files.readAllBytes(Paths.get(file.toURI())));
        return filecontents;
    }

    /**
     * Uses static methods in the Files class of NIO
     * Gets each individual line in a file, puts it in a list (List<String>)
     * A line is usually defined by {@code System.getProperty("line.separator");}
     * @param file the file to read each line from
     * @return {@code List<String>} representing each line
     * @throws IOException "if an I/O error occurs reading from the file or a malformed or unmappable byte sequence is read" (readAllLines javadoc)
     */
    public List<String> obtainWordsByLine(File file) throws IOException{
        List<String> lines = null;
        lines = Files.readAllLines(Paths.get(file.toURI()));
        return lines;
    }
    /**
     * Obtains each word in a file by reading the contents from a file and splitting it by a character
     * @param file the file to read. {@link #readFileContents(File)}
     * @param split the character to split by
     * @return an array of each word
     * @throws IOException thrown from method {@link #readFileContents(File)}
     */
    public String[] obtainWordsBySplit(File file, char split) throws IOException{
        return obtainWordsBySplit(file, String.valueOf(split));
    }

    /**
     * Obtains each word in a file by reading the contents from a file and splitting it by a string
     * @param file the file to read. {@link #readFileContents(File)}
     * @param split the string to split by
     * @return an array of each word
     * @throws IOException thrown from method {@link #readFileContents(File)}
     */
    public String[] obtainWordsBySplit(File file, String split) throws IOException{
        String contents = readFileContents(file);
        return contents.split(split);
    }

    /**
     * Checks if a string exists in a String[]
     * @param word the word to look for. Assumes that each string in the String[] could EQUAL the word, rather than if it CONTAINS the word. Use {@link #doesWordExist(String, String, boolean)} to see if it CONTAINS it.
     * To obtain a string from a String[], use {@link #toParsableString(String[])}
     * @param contents the array to search for each string in.
     * @param ignoreCase whether to ignore case or not
     * @return If the word is exactly the same (including case) returns true. If the word is a different case and {@code ignoreCase} is true, returns true. Otherwise, if it gets to the end and cannot find the word, returns false.
     */
    public boolean doesWordExist(String word, String[] contents, boolean ignoreCase){
        for(int i = 0; i < contents.length; i++){
            String w = contents[i];
            if(w.equals(word)) return true;//Word exists
            else if (w.equalsIgnoreCase(word)){ //Word exists in different case
                if(ignoreCase) return true;
                else continue;
            } 
            else continue; //That word isn't it!
        }
        return false; //Word does not exist
    }

    /**
     * Checks if a string exists in another string. Check is using the CONTAINS method.
     * You can always use this method for a {@code String[]} or {@code List<String>}
     * @param word the word to look for
     * @param contents the contents to look for the word in
     * @param ignoreCase whether to ignore case or not
     * @return If the word is exactly the same (including case) returns true. If the word is a different case and {@code ignoreCase} is true, returns true. Otherwise returns false.
     */
    public boolean doesWordExist(String word, String contents, boolean ignoreCase){
        if(ignoreCase){
            return containsIgnoreCase(word, contents);
        }else{
            return word.contains(contents);
        }
    }

    /**
     * Checks if a string exists in a list of strings.
     * This method is for simplicity. It turns {@code words} into a {@code String[]} and calls {@link #doesWordExist(String, String[], boolean)}.
     * @param word the string to look for
     * @param words the list of strings to look at
     * @param ignoreCase whether to ignore case or not
     * @return If the word is exactly the same (including case) returns true. If the word is a different case and {@code ignoreCase} is true, returns true. Otherwise, if it gets to the end and cannot find the word, returns false.
     */
    public boolean doesWordExist(String word, List<String> words, boolean ignoreCase){
        String[] w = new String[words.size()];
        String contents = "";
        for(int i = 0; i < words.size(); i++){
            contents = contents + words.get(i) + " ";
        }
        w = contents.split(" ");
        return doesWordExist(word, w, ignoreCase);
    }

    /**
     * Turns a String array into a string that can be parsed for the contains method, or other similar methods.
     * This doesn't just have to be used for files, it can be used for anything
     * @param array The array to turn into a string
     * @return the String representing the array
     */
    public String toParsableString(String[] array){
        String parseString = "";
        for(int i = 0; i < array.length; i++){
            parseString = parseString + array[i] + " ";
        }
        return parseString;
    }

    /**
     * Checks if a string contains another string, ignoring case
     * @param word the string to look for
     * @param contents the string to look for the other string in
     * @return If it does contain the word, returns true. Otherwise returns false. Ignoring case.
     */
    private boolean containsIgnoreCase(String word, String contents) {
        String w = word.toLowerCase();
        String c = contents.toLowerCase();
        return c.contains(w);
    }

}