Reading from csv file give NumberFormatException? - java

I am reading datas from a csv file and set all datas into an object.At a particular point i am getting a numberformat exception (only after reading some datas)because some datas are not numbers(That is an error inside file some charecter datas in place of numerical datas,not able to use string concept because of some integration issues with main program).At that point i need to skip that line and need to move to the nextline.Can anyone please help.Any help will be highly appreciable.
reader = new CSVReader(new FileReader(parentPath+File.separator+file),',','"');
while ((nextLine = reader.readNext()) != null &&nextLine.length!=0 ) {
encap.setPrice((nextLine[5]));
String mrp=encap.getPrice().split("[,]")[0];
try {
encap.setProduct_price(Double.parseDouble(mrp));
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Note:I need to skip and read next line onwards when ever numberformat exception occurs for a particular line.(value is getting correctly but my program stops whenever a numberformat exception occurs.......
encap is the object of my class....

Expand the scope of your try catch. Brute force, put try just below while and include ALL code in that while block inside that try block.

It looks like your try..catch is already in the right place. Just make a new encap for each record and it should behave as you want:
List<Encap> encaps = new ArrayList<Encap>(); // <- create list of results
reader = new CSVReader(new FileReader(parentPath+File.separator+file),',','"');
while ((nextLine = reader.readNext()) != null &&nextLine.length!=0 ) {
Encap encap = new Encap(); // <- create a new instance for this line
encap.setPrice(nextLine[5]);
String mrp=encap.getPrice().split("[,]")[0];
try {
encap.setProduct_price(Double.parseDouble(mrp));
encaps.add(encap); // <- add this result to the list only if parsed ok
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Related

Split() fails generating java.lang.ExceptionInInitializerError . How to remove this error?

i am doing splitting on one line of a text file,however i am getting error
java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at String[] num= firstline.split(","); line.Can anyone please tell where am i wrong
public class split {
private static java.io.File file;
private static BufferedReader reader;
static int noOfLines=0;
static {
try {
file = new java.io.File("/home/madhu95/Desktop/data.txt");
reader = new BufferedReader(new FileReader(String.valueOf(file)));
while (reader.readLine() != null) {
noOfLines++;
}
System.out.println(noOfLines);
String firstline=reader.readLine();
String[] num= firstline.split(",");
int numberofmobile=Integer.parseInt(num[0]);
System.out.println(numberofmobile);
int numberofDept=Integer.parseInt(num[1]);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
while (reader.readLine() != null) {
noOfLines++;
}
This consumes the stream. After this loop is done, you're at the end of the file.
String firstline=reader.readLine();
So this is a lie then - it's not the first line. Not anymore. By counting lines, you are no longer there. In fact, firstline is always going to be null here.
String[] num= firstline.split(",");
. where the thing to the left of it is null, gets you an NPE. You don't catch that, so, your initialization fails. Don't catch that exception - fix the problem where you've forwarded through the entire file by counting lines.
EDIT: Adding a solution that most likely solves all your problems.
Given that you want to know the # of lines before you process them, you'd either need to read the file twice or completely rewrite your logic to no longer need to know # of lines in advance. Complicated, so, instead, what if you don't process the file, but you process a List<String> - which knows how many lines it has (list.size() will get you that information). Then, first read the file into a list of lines, and then take it from there:
import java.nio.file.*;
List<String> lines =
Files.readAllLines(Paths.get("/Path/to/your/data.txt"));
// ....

Nested Try-Catch Block Not Catching Exception

My program is attempting to scan through my directory in search of the existence of .cmp or .txt files.
If fileName were to equal "test" and if neither test.cmp nor test.txt files existed, my program would still throw a FileNotFoundException despite my try-catch block under the first catch. I've tried moving the second try-catch block around, but nothing seems to work – everything I test the code out with a file that doesn't exist still ends up throwing an exception.
public int checkFileExistence() {
BufferedReader br = null;
int whichFileExists = 0;
try {//check to see if a .cmp exists
br = new BufferedReader(new FileReader(fileName + ".cmp"));
whichFileExists = 0;// a .cmp exists
}
catch (IOException e){ //runs if a .cmp file has not been found
try {//check to see if a .txt file exists
br = new BufferedReader(new FileReader(fileName + ".txt"));
whichFileExists = 1;//a .txt file exists
}
catch (IOException e2) {//if no .txt (and .cmp) file was found
e2.printStackTrace();
whichFileExists = 2; //no file exists
}
}
finally {
try {
br.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return whichFileExists;
}
I would expect the program to work, but each time I test the program, the program throws a FileNotFoundException where it says "test.txt" doesn't exist.
It is printing that exception because of this line:
e2.printStackTrace();
It's working as you are expecting, just printing the error it got. You can remove these printStackTrace() calls if you don't want to see them. Well, don't remove the one in the last catch block, otherwise you would never know if there is a problem there.
On a separate note, this design is totally based on exceptions, which is not recommended. I'm sure there are methods in the File class to check for existence of files.
This program is working as expected...
catch (IOException e2) {//if no .txt (and .cmp) file was found
e2.printStackTrace();
whichFileExists = 2; //no file exists
}
Above catch clause catches your IOException and prints it with e2.printStackTrace();

How can I increment a number in a file by an amount?

I have got a .txt file which stores a players' money. I need this file to increment or detriment a certain amount depending on if the player kills something or if they buy something from the shop.
The issue is that I do not know how to actually increment or detriment the contents. I can delete/recreate the .txt file with the new money, however because multiple threads will be accessing the file, then there is the risk that the file may not exist due to it being deleted and not regenerated yet.
Just to clarify, there will only be one thread at a time modifying the file. Other threads will only be reading the file.
So how would I do this without deleting the data/file first?
Here is the code ,read file first and then increment it and store again -
BufferedWriter out = null;
try {
// Read File Contents - score
BufferedReader br = new BufferedReader(new FileReader("c:\\a.txt"));
String storedScore="0";
int storedScoreNumber = 0;
while ((storedScore = br.readLine()) != null) {
storedScoreNumber=(Integer.parseInt(storedScore==null?"0":storedScore));
}
// Write File Contents - incremented socre
out = new BufferedWriter(new FileWriter("c:\\a.txt", false));
out.write(String.valueOf(storedScoreNumber+1));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Have a singleton data accessor with a queue so that it is the only one manipulating the file. If necessary acknowledge to client threads after the write.

Try-Catch-Finally - Final Block not recognising variable

firstly I know I should be using a try-catch with resources, however I don't currently have the most up to date JDK on my system.
I have the following code below, and am trying to ensure the resource reader is closed using the finally block, however the code below doesn't compile for two reasons. Firstly is that reader may have not been initialized and secondly that close() should be caught within its own try-catch. Dont both of these reasons defeat the object of the initial try-catch block?
I can solve the issue with the finally block close() statement by putting it in its own try-catch. However this still leaves the compile error about reader not being initialized?
I'm presuming I have gone wrong somewhere? Help appreciated!
Cheers,
public Path [] getPaths()
{
// Create and initialise ArrayList for paths to be stored in when read
// from file.
ArrayList<Path> pathList = new ArrayList();
BufferedReader reader;
try
{
// Create new buffered read to read lines from file
reader = Files.newBufferedReader(importPathFile);
String line = null;
int i = 0;
// for each line from the file, add to the array list
while((line = reader.readLine()) != null)
{
pathList.add(0, Paths.get(line));
i++;
}
}
catch(IOException e)
{
System.out.println("exception: " + e.getMessage());
}
finally
{
reader.close();
}
// Move contents from ArrayList into Path [] and return function.
Path pathArray [] = new Path[(pathList.size())];
for(int i = 0; i < pathList.size(); i++)
{
pathArray[i] = Paths.get(pathList.get(i).toString());
}
return pathArray;
}
There is no other way then initialize your buffer and catch the exception. The compiler is always right.
BufferedReader reader = null;
try {
// do stuff
} catch(IOException e) {
// handle
} finally {
if(reader != null) {
try {
reader.close();
} catch(IOException e1) {
// handle or forget about it
}
}
}
The method close will always need a try-catch-block since it declares that it could throw an IOException. It doesn't matter if the call is in a finally block or somewhere else. It just needs to be handled. It is a checked exception.
Read must also be initialized just by null. IMHO this is super useless, but that's Java. That is how it works.
Instead check if reader is null or not and then close it accordingly like below (you should call close() on reader only if it's not null or if it's been already instantiated else you will end up getting null reference exception).
finally
{
if(reader != null)
{
reader.close();
}
}

Java File Handling, what did I do wrong?

Wrote up a basic file handler for a Java Homework assignment, and when I got the assignment back I had some notes about failing to catch a few instances:
Buffer from file could have been null.
File was not found
File stream wasn't closed
Here is the block of code that is used for opening a file:
/**
* Create a Filestream, Buffer, and a String to store the Buffer.
*/
FileInputStream fin = null;
BufferedReader buffRead = null;
String loadedString = null;
/** Try to open the file from user input */
try
{
fin = new FileInputStream(programPath + fileToParse);
buffRead = new BufferedReader(new InputStreamReader(fin));
loadedString = buffRead.readLine();
fin.close();
}
/** Catch the error if we can't open the file */
catch(IOException e)
{
System.err.println("CRITICAL: Unable to open text file!");
System.err.println("Exiting!");
System.exit(-1);
}
The one comment I had from him was that fin.close(); needed to be in a finally block, which I did not have at all. But I thought that the way I have created the try/catch it would have prevented an issue with the file not opening.
Let me be clear on a few things: This is not for a current assignment (not trying to get someone to do my own work), I have already created my project and have been graded on it. I did not fully understand my Professor's reasoning myself. Finally, I do not have a lot of Java experience, so I was a little confused why my catch wasn't good enough.
Buffer from file could have been null.
The file may be empty. That is, end-of-file is reach upon opening the file. loadedString = buffRead.readLine() would then have returned null.
Perhaps you should have fixed this by adding something like if (loadedString == null) loadedString = "";
File was not found
As explained in the documentation of the constructor of FileInputStream(String) it may throw a FileNotFoundException. You do catch this in your IOException clause (since FileNotFoundException is an IOException), so it's fine, but you could perhaps have done:
} catch (FileNotFoundException fnfe) {
System.err.println("File not fonud!");
} catch (IOException ioex {
System.err.println("Some other error");
}
File stream wasn't closed
You do call fin.close() which in normal circumstances closes the file stream. Perhaps he means that it's not always closed. The readLine could potentially throw an IOException in which case the close() is skipped. That's the reason for having it in a finally clause (which makes sure it gets called no matter what happens in the try-block. (*)
(*) As #mmyers correctly points out, putting the close() in a finally block will actually not be sufficient since you call System.exit(-1) in the catch-block. If that really is the desired behavior, you could set an error flag in the catch-clause, and exit after the finally-clause if this flag is set.
But what if your program threw an exception on the second or third line of your try block?
buffRead = new BufferedReader(new InputStreamReader(fin));
loadedString = buffRead.readLine();
By this point, a filehandle has been opened and assigned to fin. You could trap the exception but the filehandle would remain open.
You'll want to move the fin.close() statement to a finally block:
} finally {
try {
if (fin != null) {
fin.close();
}
} catch (IOException e2) {
}
}
Say buffRead.readLine() throws an exception, will your FileInputStream ever be closed, or will that line be skipped? The purpose of a finally block is that even in exceptional circumastances, the code in the finally block will execute.
There are a lot of other errors which may happen other than opening the file.
In the end you may end up with a fin which is defined or not which you have to protect against null pointer errors, and do not forget that closing the file can throw a new exception.
My advice is to capture this in a separate routine and let the IOExceptions fly out of it :
something like
private String readFile() throws IOException {
String s;
try {
fin = new FileInputStream(programPath + fileToParse);
buffRead = new BufferedReader(new InputStreamReader(fin));
s = buffRead.readLine();
fin.close();
} finally {
if (fin != null {
fin.close()
}
}
return s
}
and then where you need it :
try {
loadedString = readFile();
} catch (IOException e) {
// handle issue gracefully
}

Categories