Reading from a comma separated value file [duplicate] - java

This question already has answers here:
Read CSV with Scanner()
(8 answers)
Closed 5 years ago.
I am attempting to read from a .csv file for my program but we have never read from a .csv file before in my class. I'm not quite sure how to go about it, but this is my attempt so far. I imagine that I am missing some kind of loop that loops through every line of the file but I am not sure how to go about doing that.
Bank bank = new Bank();
Scanner infile = new Scanner("C:/Users/Josh/Desktop/prog5input.csv");
Scanner s2 = new Scanner(infile.nextLine());
int accountType = 0;
String accountHolder = "";
double accountInitial = 0.0;
double accountRate = 0.0;
System.out.println("Program 5, Josh Correia, cssc0491");
System.out.println("Creating accounts...");
s2.useDelimiter(",");
if (s2.hasNextInt()) accountType = s2.nextInt();
if (s2.hasNext()) accountHolder = s2.next();
if (s2.hasNextDouble()) accountInitial = s2.nextDouble();
if (s2.hasNextDouble()) accountRate = s2.nextDouble();
bank.addNewAccount(new SavingsAccount(accountHolder, accountInitial, accountRate));
This is the file that I am reading from:
1,Waterford Ellingsworth, 4350.0, 0.002
2,Bethanie Treadwell, 500.0, 0.35
3,Ira Standish, 50000, 0.1, 59, 0.1
4,Debi Cardashian, 5100, 0.0

File file = new File("C:/Users/Josh/Desktop/prog5input.csv");
Scanner sc = new Scanner(file);
while(sc.hasNextLine()){
String str = sc.nextLine();
String[] arr = str.split(",");
int accountType = Integer.valueOf(((String)arr[0]).trim());
......
}
You can refer to this link about other ways to read file.

you could set it to an actual String and then to a ArrayList via the spilt method :
String str = " ";
ArrayList<String> elephantList = Arrays.asList(str.split(","));

Related

Error handling when reading from txt file [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
I have my program which reads from a txt file, then turns txt information into a car object and adds them to an arraylist.
try {
String filePath = "car.txt";
File f = new File(filePath);
Scanner sc = new Scanner(f);
List<Car> car = new ArrayList<Car>();
while(sc.hasNextLine()){
String newLine = sc.nextLine();
String[] details = newLine.split(" ");
String brand = details[0];
String model = details[1];
double cost = Double.parseDouble(details[2]);
Car c = new Car(brand, model, cost);
Car.add(c);
}
However, If a line from the txt file does not contain the three components then it crashes. How would I check if the line contains all 3 components, if not print a message then terminate?
Stack trace -
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Main.loadPerson(Main.java:31)
at Main.main(Main.java:12)
You need to check for the length of details is 3, if not exit as shown below:
String[] details = newLine.split(" ");
if(details.length != 3) {
System.out.println("Incorrect data entered !! Please try again !!! ");
return;
} else {
String brand = details[0];
String model = details[1];
double cost = Double.parseDouble(details[2]);
Car c = new Car(brand, model, cost);
Car.add(c);
}
You can check the length of return array from split by:
int count = details.length;
and then decide what to do
check length before accessing elements,
try the pattern \\s+ to avoid trimming spaces, there is a typo in your code where adding Car to car list
while (sc.hasNextLine()) {
String newLine = sc.nextLine();
String[] details = newLine.split("\\s+");
if (details.length == 3) {
String brand = details[0];
String model = details[1];
double cost = Double.parseDouble(details[2]);
Car c = new Car(brand, model, cost);
car.add(c);
} else {
System.out.println("Invalid input");
}
}
If the file doesn't contain the 3 components, then details will be empty. use this instead.
if(details.length() != 3){
System.out.println("Invalid .txt file!");
break;
}

java.lang.NumberFormatException: For input string when using scanner to read the file

I am not sure why I am receiving this error and what's the fix to it in the following snippet of code:
String srcFile=args[0];
Scanner fileIn = new Scanner(srcFile);
// if (fileIn.isFile() && fileIn.canRead())
CarDB carDatabase = new CarDB();
while(fileIn.hasNext())
{
String[] line = fileIn.nextLine().split(",");
double mpg = Double.parseDouble(line[0]);
int cylinders = Integer.parseInt(line[1]);
int power = Integer.parseInt(line[2]);
int year = Integer.parseInt(line[3]);
int region = Integer.parseInt(line[4]);
String makerName = line[5].trim();
String carName = line[6].trim();
carDatabase.addCar(makerName, carName, mpg, cylinders, power, year, region);// add car
carDatabase.addMaker(makerName);//add maker to list
}
and line 36 is : double mpg = Double.parseDouble(line[0]);
Error is:
java CarDBMain cars.txt
java.lang.NumberFormatException: For input string: "cars.txt"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1250)
at java.lang.Double.parseDouble(Double.java:540)
at CarDBMain.main(CarDBMain.java:36)
You are having this Scanner fileIn = new Scanner("cars.txt"); so your first line will be "cars.txt"
Scanner fileIn = new Scanner(new File(srcFile));//Or probably path of file
Here create file and pass the commandline argument,means file path,to File constructor and pass that file to Scanner.
You are passing file name as String to Scanner.
Constructors
Scanner(File source)<---Takes File you want to read
Scanner(String source)<----Takes String you want to read
etc.

Java Delete a line from txt after reding the file [duplicate]

This question already has answers here:
Java - delete line from text file by overwriting while reading it
(3 answers)
Closed 8 years ago.
I have this file
1007 book1 5 3
1004 book2 4 1
1003 book3 3 0
1002 book4 2 1
and I am trying to delete the book number 1004 from the file, but before that I let the user enter the number of the book that he wants to delete.
First check if the book exists in the file or not, if the book is exists I delete it if not show "the book does not exists".
Scanner kb = new Scanner(System.in);
FileInputStream book = new FileInputStream("input.txt");
Scanner infile = new Scanner(book);
FileOutputStream out = new FileOutputStream("output.txt");
PrintWriter pw = new PrintWriter(out);
boolean found = false;
System.out.print("Enter the bookID : ");
int bID = kb.nextInt();
while(infile.hasNext()){
int id = infile.nextInt();
String title = infile.next();
int quantity = infile.nextInt();
int bQuantity = infile.nextInt();
if(bID == id){
found = true;
}
if(found == true){
pw.printf("%8d\t%-30s\t%8d\t%8d", infile.nextInt(), infile.next(), infile.nextInt(), infile.nextInt());
infile.nextLine();
System.out.println("The book has been deleted");
break;
}
}
if(found == false)
System.out.print("Not found");
pw.close();
infile.close();
I am trying to print all the file with out the book I have deleted.
You will need a book class, like this:
public class Book {
private int series;
private String name;
private int intA;
private int intB;
public Book(int series,String name, int intA, int intB) {
this.series = series;
this.name = name;
this.intA = intA;
this.intB = intB;
}
....
.... (add other methods as needed, you will definitely need a
toString() method, and getIntA(), getIntB(), getSeriesNum(),
getName() etc.)
}
When you use scanner to read the file, read them into an arraylist of type Book. When user enter a number, use a for loop to find the Book that matches that number, and remove that book object from your arraylist.
Also, try to keep data in memory and not write files too often. Writing files to disks is very inefficient comparing with changing data in memory. Once user is done with all his/her operations, you can use a printwriter to write the data to your file.
To read your file into this array of objects, you can do this:
public static ArrayList<Book> readbooklist() {
ArrayList<Book> booklist = new ArrayList<Book>();
File file = new File("path/filename.fileextension");
try {
Scanner scnr = new Scanner(file);
while (scnr.hasNextLine()) {
String entry = scnr.nextLine();
String [] parts = entry.split("\t"); // Depends on how data was delimited
int series = Integer.parseInt(parts[0]);
int intA = Integer.parseInt(parts[2]);
int intB = Integer.parseInt(parts[3]);
Book single = new Book(series, parts[1], intA, intB);
booklist.add(single);
}
scnr.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found!");
}
return booklist;
}
Remember to import proper dependency at the beginning of your class. Wish it helps!
I'd recommend to use a Map to store each line as value and the Id as the key only once. That way you don't have to reopen the file and read it each time you want to remove or add an entry, all you have to do is remove it and add it to the map. Once you are done, you can overwrite the old file you have by the values stored in the map or just create a new temp file to hold the data, delete the old file and then rename the temp file with old file's name
Store all the lines you would like to save in a String and close the scanner. Create a printwriter, print the string to the file and close it.
Example code:
File file = new File("yourTextFile.txt");
Scanner in = new Scanner(file);
String saveThisToFile = "";
while (in.hasNext()) {
String temp = in.nextLine();
if (condition to be true if you whant to keep this line) {
saveThisToFile += temp + "\n";
}
}
in.close();
PrintWriter printWriter = new PrintWriter(file);
printWriter.print(saveThisToFile);
printWriter.close();

TimeSorter: Read time(form of hh:mm a.m.) file using Scanner

Here is how far I've done.
try
{
Scanner keyb = new Scanner(System.in);
System.out.print("Enter the name of the input file-> ");
String inFileName = keyb.next();
System.out.print("Enter the name of the output file-> ");
String outFileName = keyb.next();
ArrayList<Time> roster = new ArrayList<Time>();
Scanner fileIn = new Scanner(new File(inFileName));
while (fileIn.hasNext())
{
int hours = fileIn.nextInt();
int minutes = fileIn.nextInt();
String meridian = fileIn.next();
roster.add(new Time(hours,minutes,meridian));
}
fileIn.close();
Basically, what I have to do is read 'appointment.txt' file that has all different time that is in 11:30 a.m. form to sort it in order and save it different file name. But because of colon(:) in between hour and minutes, my while loop can't read time correctly and make error. What would make my while loop working?
Your while-loop is not correctly working because you check for fileIn.hasNext(), but afterwards use fileIn.nextInt() and fileIn.next() in different ways.
What you probably want to use is:
while (fileIn.hasNextLine()) {
String line = fileIn.nextLine();
String[] bigParts = line.split(" ");
String[] timeParts = bigParts[0].split(":");
roster.add(new Time(
Integer.parseInt(timeParts[0]),
Integer.parseInt(timeParts[1]),
bigParts[1]
));
}
This reads the file line by line, then takes the line it has read. Following it splits the text up in three parts, first by (blank), then by : (colon).
UPDATE: Added Integer.parseInt() as it was originally done aswell.

Reading from text file and storing contents in separate arrays

I have a text file containing
r0, 0.5, 1
r1, 0.6, -1
r2, 0.2, 1
I want read the file and store each column in a separate array in java. This is the code I have been writing. I am only getting garbage values in the records. Also, I am not able read the float values. Please tell me how to fix this.
public class Model{
private String modelname ;
private String[] records ;
private int[] targets ;
private float[] scores ;
public Model(String name_model, String path) throws NumberFormatException, IOException {
this.modelname = path+name_model ;
System.out.println(this.modelname);
BufferedReader bufferReader = new BufferedReader(new FileReader(path+name_model));
String line=null;
int t=0;
while((line = bufferReader.readLine())!=null) {
System.out.println(line);
//String[] strar = line.split(",");
//String[] strar = line.split("\\s*,\\s*") ;
int k=1 ;
for(String part : line.split(",")) {
if (k==1) {
System.out.println(part.trim());
this.records[t] = part.trim() ;
}
if (k==3)
this.targets[t] = Integer.valueOf(part.trim()) ;
if (k==2)
this.scores[t] = Float.parseFloat(part.trim()) ;
k=k+1 ;
}
System.out.println(this.records[t] + " " + this.targets[t] + " " + this.scores[t]);
t=t+1;
}
}
public static void main(String[] args) throws Exception, IOException {
String s1, s2, s3 ;
s1 = "./direc/" ;
s2 = "file1.txt" ;
s3 = s1+s2 ;
System.out.println(s3);
new Model(s2, s1);
}
}
You can simplify the parsing. You can do away with the inner loop and avoid trimming as
String[] parts = line.split(", ");
this.records[t] = parts[0];
this.scores[t] = Float.parseFloat(parts[1]);
this.targets[t] = Integer.parseInt(parts[2]);
I'm assuming you forgot to put the second comma here
r1, 0.6, -1
And, since you're using a primitive int[] use Integer.parseInt() instead of Integer.valueOf() (which returns an Integer wrapper) to avoid unnecessary unboxing.
EDIT :
You also need to initialize all of your Arrays like
private String[] records = new String[100]; // initialization is MISSING!
Since, in your case the size of the Array depends on the number of lines in your input data file it needs to be dynamic. Consider switching to an ArrayList that would grow dynamically.
private List<String> records = new ArrayList<String>();
private List<Integer> targets = new ArrayList<Integer>();
private List<Float> scores = new ArrayList<Float>();
Since, you need to use the wrapper types to be able to use collections; switch back to valueOf() methods.
String[] parts = line.split(", ");
this.records.add(parts[0]);
this.scores.add(Float.valueOf(parts[1]));
this.targets.add(Integer.valueOf(parts[2]));
If you don't use braces in the if (k==1) case, this.records[t] gets assigned the last part always. The code should be:
if (k==1) {
System.out.println(part.trim());
this.records[t] = part.trim() ;
}
Also, you're missing a comma after the 0.6 on the second line of input.
A simple way i like to use for reading files would be utilising the Scanner and File classes
so start by importing those
java.util.Scanner;
java.io.*;
then in your code (don't forget to throw IOException):
File filename = new File("filename.txt");
Scanner fileScanner = new Scanner(filename);
now if your using arrays, you need to know the size of the array in order to create it, and its type.
and considering your text file looks like this:
1.0 2.7 6.3 8.4 8.6
2.0 9.4 9.1 3.0 4.2
3.4 7.7 8.3 3.2 1.0
if your file can contain comma's
add this line after creating your scanner:
fileScanner.useDelimiter(", ")
and you would like 5 arrays containing each row of floats or integers etc...
create 5 arrays with the size (here 3), then use this loop to add each number:
int rank = 0;
double[] r1 = new double[3];
.
.
.
double[] r5 = new double[3];
while(fileScanner.hasNext())
{
if(fileScanner.hasNextDouble()) r1[rank] = fileScanner.nextDouble();
if(fileScanner.hasNextDouble()) r2[rank] = fileScanner.nextDouble();
if(fileScanner.hasNextDouble()) r3[rank] = fileScanner.nextDouble();
if(fileScanner.hasNextDouble()) r4[rank] = fileScanner.nextDouble();
if(fileScanner.hasNextDouble()) r5[rank] = fileScanner.nextDouble();
rank++;
}

Categories

Resources