簡體   English   中英

從文件中讀取一行文本並將其存儲到字符串中

[英]Reading a line of text from a file and storing it into a String

基本上,我想做的是存儲文本文件中的整行並將其存儲到一個字符串中。 該行是班級部門,班級編號和所學的學期。 例如,“ CSCE 155A-2011年秋季”。 我想將所有這些都放入一個稱為“ description”的字符串中。

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

這行代碼僅輸出第一部分CSCE。 有沒有辦法存儲整條線? 我唯一能想到的就是幾個scanner.next()和print語句,但這看起來很混亂

從String Scanner.next()上的文檔中:

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

因為您的示例行是:“ CSCE 155A-Fall 2011”,所以next()將在第一個空格處停止。

您需要的是Scanner.nextLine():

className = scanner.nextLine();

如果您使用的是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);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM