2016-04-17 16 views
0

Dies ist mein Code für die Suche nach einem bestimmten Wort in der txt-Datei, aber wenn das Wort, das ich suche, in der ersten Zeile steht, dann hat es gefunden, aber wenn das Wort auf einer anderen Zeile als Zeile ist 1 kann es nicht finden. Noch eine Sache, die ich in BufferedReader oder FileReader implementieren möchte.Suche nach einem Wort

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) { 





         } 

      } 

Antwort

0

Wenn es in jeder Zeile ein Wort ist, können Sie laden Sie einfach jedes Wort auf ein List<String> Objekt und prüfen, ob jedes Element Ihr Wort ist. Beispiel:

Wenn zwischen jedem Wort ein Leerzeichen steht, können Sie den Inhalt der Datei auf byte[] laden, dann den new String(byte[])-Konstruktor verwenden, die Zeichenfolge durch das Leerzeichen trennen und das Array nach Ihrem Wort durchsuchen. Sie können diese Methode auch verwenden, wenn Sie das Wort z. ein Doppelpunkt.

Wenn es nur eine Zeile gibt, empfehle ich BufferedReader, da es einzelne Zeilen schnell lesen kann, anstatt String-Listen oder Arrays zu verwenden.

Nachdem Sie Ihre Worte in einen der oben genannten Weisen erhalten haben, können Sie dann einfach für Ihr Wort suchen, indem jedes Wort in der Liste, Array bekommen, oder String und unter Verwendung der equals, equalsIgnoreCase oder contains Methoden.

Ich schrieb eine Klasse, das tut, was Sie wollen:

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); 
    } 

} 
Verwandte Themen