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". I want to put all of that into one string called "description".
className = scanner.next();
System.out.println(className);
This line of code will only output the first part, 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
From the docs on 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.
Because your example line is: "CSCE 155A - Fall 2011", it next() will stop at the first space.
What you need is Scanner.nextLine():
className = scanner.nextLine();
If you are using Java 7, may be you want to use NIO.2, eg:
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);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.