2015-07-12 36 views
4

就像標題所說,我試圖編寫一個程序,它可以讀取文本文件中的單個單詞並將它們存儲到String變量中。我知道如何使用FileReaderFileInputStream來閱讀一個單一的char,但我想這不會工作。一旦我輸入單詞我試圖用我的程序中的其他字符串變量與使用.equals進行比較,所以如果我可以導入爲字符串將是最好的。我也可以從文本文件輸入整行作爲字符串,在這種情況下,我只是在我的文件的每一行放一個字。如何從文本文件輸入單詞並將它們存儲到字符串變量中?編輯: 好吧,那種重複的幫助。它可能適用於我,但我的問題有點不同的原因是因爲重複只說明如何讀取一行。我試圖讀取行中的單詞。所以基本上分割線字符串。如何從文本文件Java中讀取單個單詞(或行)?

+1

可能重複的[讀下一個單詞在java](http://stackoverflow.com/questions/4574041/read-next-word-in-java) –

+0

@EricLeibenguth之類的,閱讀上面的編輯 –

+1

不,不,仔細看看答案:下一行使用'Scanner.nextLine()',下一個單詞使用'Scanner.next()'。 –

回答

5

從文本文件中讀取行,你可以使用這個(使用try-與資源):

String line; 

try (
    InputStream fis = new FileInputStream("the_file_name"); 
    InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8")); 
    BufferedReader br = new BufferedReader(isr); 
) { 
    while ((line = br.readLine()) != null) { 
     // Do your thing with line 
    } 
} 

要塊的行爲單個單詞,你可以使用String.split

while ((line = br.readLine()) != null) { 
    String[] words = line.split(" "); 
    // Now you have a String array containing each word in the current line 
} 
+0

好吧,謝謝!這正是我所期待的。 –

1

您必須使用StringTokenizer!在此示例,並閱讀該String Tokenizer

private BufferedReader innerReader; 
public void loadFile(Reader reader) 
     throws IOException { 
    if(reader == null) 
    { 
     throw new IllegalArgumentException("Reader not valid!"); 
    } 
     this.innerReader = new BufferedReader(reader); 
    String line; 
    try 
    { 
    while((line = innerReader.readLine()) != null) 
    { 
     if (line == null || line.trim().isEmpty()) 
      throw new IllegalArgumentException(
        "line empty"); 
     //StringTokenizer use delimiter for split string 
     StringTokenizer tokenizer = new StringTokenizer(line, ","); //delimiter is "," 
     if (tokenizer.countTokens() < 4) 
      throw new IllegalArgumentException(
        "Token number not valid (<= 4)"); 
     //You can change the delimiter if necessary, string example 
     /* 
     Hello/bye , hi 
     */ 
     //reads up "/" 
     String hello = tokenizer.nextToken("/").trim(); 
     //reads up "," 
     String bye = tokenizer.nextToken(",").trim(); 
     //reads up to end of line 
     String hi = tokenizer.nextToken("\n\r").trim(); 
     //if you have to read but do not know if there will be a next token do this 
     while(tokenizer.hasMoreTokens()) 
     { 
      String mayBe = tokenizer.nextToken("."); 
     } 
    } 
    } catch (Exception e) { 
     throw new IllegalArgumentException(e); 
    } 
} 
+0

好的,謝謝,我可能不得不對這個String Tokenizer做一些研究,因爲我從未見過它。幾分鐘後我會回到這個問題。 –

+0

我改變了一些東西,我希望你有幫助 –

+1

感謝您的答案@MicheleLacorte。這是偉大的,並且我deffinetly去看看這個,但現在sporks答案是更多我正在尋找,並且對我來說更容易理解(我不是很好,但LOL) –

5

這些都是非常複雜的答案。我相信他們都很有用。但我更喜歡淡雅Scanner

public static void main(String[] args) throws Exception{ 
    Scanner sc = new Scanner(new File("fileName.txt")); 
    while(sc.hasNext()){ 
     String s = sc.next(); 
     //..... 
    } 
} 
+1

雅,deffinetly同意,他們對我來說相當複雜。我基本上使用了標記的重複問題的答案和@spork答案的組合。儘管謝謝你的回答! –

1

在java8你可以做類似如下:

import java.io.IOException; 
import java.nio.file.Files; 
import java.nio.file.Paths; 
import java.util.Arrays; 
import java.util.Collections; 
import java.util.List; 
import java.util.stream.Collectors; 

public class Foo { 
    public List<String> readFileIntoListOfWords() { 
     try { 
      return Files.readAllLines(Paths.get("somefile.txt")) 
       .stream() 
       .map(l -> l.split(" ")) 
       .flatMap(Arrays::stream) 
       .collect(Collectors.toList()); 
     } 
     catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return Collections.emptyList(); 
    } 
} 

雖然我懷疑是分裂的說法可能需要改變,例如至從一個詞的末尾修整標點符號

相關問題