I am trying to use the Java Scanner class to read a text file all the way through and section each of the strings into the respected datatype such as a string "123" into long number = 123.
Here is my code:
public static void main(String[] args) throws NoSuchElementException, FileNotFoundException, IOException{
String filelocation = "file.txt";//this is for file path
ProductList p = new ProductList();
try {
File myObj = new File(filelocation);
Scanner src = new Scanner(myObj);
while (src.hasNextLine()) {
long id = Long.parseLong(src.nextLine());
String data = src.nextLine();
double op = Double.parseDouble(src.nextLine());
double cp = Double.parseDouble(src.nextLine());
String space = src.nextLine(); //without this line I get an error input ""
System.out.println(id "\n" data "\n" op "\n" cp "\n" space);
}
src.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
Here is the content in the text file:
121
Dining Table
129.99
119.99
1007
Leather Storage Ottoman
199.99
199.99
264
Gas-Powered Chainsaw
249.99
189.99
763
Protected Cruiser Takasago, 1898, 1/350, resin model kit
239.99
199.99
7465
Vacuum Cleaner, Green, 2252
99.99
89.99
354
Alienware 55 OLED Gaming Monitor - AW5520QF
4049.99
3039.99
Here is the output:
I do not understand why it is not printing the last item and how to take care of the error no line found. I understand you can throw an exception for illegals but I try that and still get the error.
CodePudding user response:
At the end of file, an empty line is missing. In fact, it throws an exception when tries to read the last space at line String space = src.nextLine();
.
You can fix checking if the last space exists.
public static void main(String[] args) throws NoSuchElementException, FileNotFoundException, IOException{
String filelocation = "file.txt";//this is for file path
ProductList p = new ProductList();
try {
File myObj = new File(filelocation);
Scanner src = new Scanner(myObj);
while (src.hasNextLine()) {
long id = Long.parseLong(src.nextLine());
String data = src.nextLine();
double op = Double.parseDouble(src.nextLine());
double cp = Double.parseDouble(src.nextLine());
if (src.hasNextLine()) {
src.nextLine(); //read the space just if exists and it is not necessary to put it in a variable
}
System.out.println(id "\n" data "\n" op "\n" cp "\n");
}
src.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
CodePudding user response:
As mentioned in the comment (by Federico klez Culloca):
It's expecting an empty line at the end of the file.
Therefore I believe it is better to read the file one line at a time, in a loop, and process each line in the loop body.
I also recommend using try-with-resources as well as NIO.2.
According to the code in your question, it appears that the only thing you do with the data, that you read from the file, is to print it.
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ReadText {
public static void main(String[] args) {
Path path = Paths.get("file.txt");
try (BufferedReader br = Files.newBufferedReader(path)) {
String line = br.readLine();
int count = 0;
while (line != null) {
count ;
int ndx = count % 5;
switch (ndx) {
case 0:
System.out.println();
break;
case 1:
long id = Long.parseLong(line.trim());
System.out.println(id);
break;
case 2:
String data = line;
System.out.println(data);
break;
case 3:
double op = Double.parseDouble(line);
System.out.println(op);
break;
case 4:
double cp = Double.parseDouble(line);
System.out.println(cp);
break;
default:
// Should never get here!
throw new RuntimeException("Unhandled: " ndx);
}
line = br.readLine();
}
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
Note that method trim()
is due to the fact that there is a single space after 121 in the first line of the text file content (which I copied from your question).
CodePudding user response:
public static void main(String... args) throws FileNotFoundException {
List<Product> products = readProductsFromFile(new File("file.txt"));
printProducts(products);
}
public static List<Product> readProductsFromFile(File file) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
scan.useLocale(Locale.ENGLISH);
List<Product> products = new ArrayList<>();
while (scan.hasNext()) {
long id = scan.nextLong();
scan.nextLine();
String data = scan.nextLine();
double op = scan.nextDouble();
double cp = scan.nextDouble();
products.add(new Product(id, data, op, cp));
}
return products;
}
}
private static void printProducts(List<Product> products) {
boolean emptyLine = false;
for (Product product : products) {
if (emptyLine)
System.out.println();
emptyLine = true;
System.out.format("%d\n%s\n%.2f\n%.2f\n", product.id, product.data, product.op, product.cp);
}
}
public static final class Product {
public final long id;
public final String data;
public final double op;
public final double cp;
public Product(long id, String data, double op, double cp) {
this.id = id;
this.data = data;
this.op = op;
this.cp = cp;
}
}