简体   繁体   English

从文件中读取一行文本并将其存储到字符串中

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

Basically what I'm trying to do is store an entire line from a text file and store it into one string. 基本上,我想做的是存储文本文件中的整行并将其存储到一个字符串中。 The line is the class department, the class number, and the semester it is being taken. 该行是班级部门,班级编号和所学的学期。 For example, "CSCE 155A - Fall 2011". 例如,“ CSCE 155A-2011年秋季”。 I want to put all of that into one string called "description". 我想将所有这些都放入一个称为“ description”的字符串中。

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

This line of code will only output the first part, CSCE. 这行代码仅输出第一部分CSCE。 Is there a way to store the entire line? 有没有办法存储整条线? The only thing I can think of is several scanner.next() and print statements, but that seems messy 我唯一能想到的就是几个scanner.next()和print语句,但这看起来很混乱

From the docs on String Scanner.next(): 从String Scanner.next()上的文档中:

Finds and returns the next complete token from this scanner. 查找并返回此扫描仪的下一个完整令牌。 A complete token is preceded and followed by input that matches the delimiter pattern. 完整的标记在其前面,然后是与定界符模式匹配的输入。 This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true. 即使先前调用hasNext()返回true,此方法也可能在等待输入扫描时阻塞。

Because your example line is: "CSCE 155A - Fall 2011", it next() will stop at the first space. 因为您的示例行是:“ CSCE 155A-Fall 2011”,所以next()将在第一个空格处停止。

What you need is Scanner.nextLine(): 您需要的是Scanner.nextLine():

className = scanner.nextLine();

If you are using Java 7, may be you want to use NIO.2, eg: 如果您使用的是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