2013-11-15 156 views
0

基本上我想要做的是從文本文件存儲整行並將其存儲到一個字符串中。該線是班級部門,班級編號和正在學習的學期。例如,「CSCE 155A - 2011年秋季」。我想把所有這些放到一個名爲「description」的字符串中。從文件中讀取一行文本並將其存儲到字符串中

className = scanner.next(); 
System.out.println(className); 

這行代碼只會輸出第一部分,CSCE。有沒有辦法儲存整條生產線?我能想到的唯一的事情就是幾個scanner.next()和打印報表,但似乎凌亂

+2

你想要[' nextLine()'](http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine())。 – rgettman

+0

不要忘記,如果答案滿意地解決了您的問題,您可以[接受它](http://meta.stackexchange.com/a/5235/227183)。 –

回答

0

從這串Scanner.next()文檔:

查找並從該掃描儀返回下一個完整標記。 A 完整令牌的前後是與 定界符模式匹配的輸入。即使先前調用hasNext()返回true,此方法也可能在等待輸入爲 掃描時阻塞。

因爲您的示例行是:「CSCE 155A - Fall 2011」,它的next()將停在第一個空格處。

你需要的是Scanner.nextLine():

className = scanner.nextLine(); 
0

如果您使用的是Java 7,可能要使用NIO.2,如:

public static void main(String[] args) throws IOException { 
    // The file to read 
    File file = new File("test.csv"); 

    // The charset for read the file 
    Charset cs = StandardCharsets.UTF_8; 

    // Read all lines 
    List<String> lines = Files.readAllLines(file.toPath(), cs); 
    for (String line : lines) { 
     System.out.println(line); 
    } 

    // Read line by line 
    try (BufferedReader reader = Files.newBufferedReader(file.toPath(), cs)) { 
     for (String line; (line = reader.readLine()) != null;) { 
      System.out.println(line); 
     } 
    } 
} 
相關問題