Try and Catch Error in Java - java

I need to write a program that reads a text file and calculates different things, however, if the file name is not found, it should print an error message with the following error message from a try and catch block:
java.io.FileNotFoundException: inputValues (The system cannot find the file specfied)
.......
However, I am instead receiving this error message:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Project6.main(Project.java:50)
Here is part of my code:
Scanner console = new Scanner(System.in);
System.out.print("Please enter the name of the input file: "); // Prompts User to Enter Input File Name
String inputFileName = console.nextLine(); // Reads Input File Name
Scanner in=null; //
try
{
in = new Scanner(new File(inputFileName)); // Construct a Scanner Object
}
catch (IOException e) // Exception was Thrown
{
System.out.print("FileNotFound Exception was caught, the program will exit."); // Error Message Printed because of Exception
e.printStackTrace();
}
int n = in.nextInt(); // Reads Number of Line in Data Set from First Line of Text Document
double[] array = new double[n]; // Declares Array with n Rows
Line 50 is: int n = in.nextInt();
Other than printing the incorrect error message, my program runs perfectly fine.
Any/all help would be greatly appreciated!

Your exception thrown at the line in.nextInt() where you are trying to read an integer but the scanner found something else. If you need to take all of them as a single error you can put them in the same try catch block as follows.
Scanner in=null; //
try
{
in = new Scanner(new File(inputFileName));
// Construct a Scanner Object
int n = in.nextInt();
// Reads Number of Line in Data Set from First Line of Text Document
double[] array = new double[n];
} catch (IOException e)
// Exception was Thrown
{
System.out.print("FileNotFound Exception was caught, the program will exit.");
// Error Message Printed because of Exception
e.printStackTrace();
} catch (InputMismatchException e)
// Exception was Thrown
{
System.out.print("Integer not found at the beginning of the file, the program will exit.");
// Error Message Printed because of Exception
e.printStackTrace();
}

Ugly, badly formatted code is hard to read and understand. It's part of why you're having trouble.
This is simpler: start with this.
package cruft;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* MessyFileDemo
* #author Michael
* #link https://stackoverflow.com/questions/31106118/try-and-catch-error-in-java
* #since 6/28/2015 8:20 PM
*/
public class MessyFileDemo {
public static void main(String[] args) {
List<Double> values;
InputStream is = null;
try {
String inputFilePath = args[0];
is = new FileInputStream(inputFilePath);
values = readValues(is);
System.out.println(values);
} catch (IOException e) {
e.printStackTrace();
} finally {
close(is);
}
}
private static void close(InputStream is) {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static List<Double> readValues(InputStream is) throws IOException {
List<Double> values = new ArrayList<>();
if (is != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
String [] tokens = line.split(",");
for (String token : tokens) {
values.add(Double.parseDouble(token));
}
}
}
return values;
}
}

Related

catch error while reading file from args (java)

Can someone please explain to me why I'm getting the catch error ?
I am trying to read values (numbers) from the file I passed in args.
And I do not quite understand where the problem comes from.
import java.util.Scanner;// Import the Scanner class to read text files
import java.io.File;// Import the File class
import java.io.FileNotFoundException;// Import this class to handle errors
import java.io.*;
public class main extends GeneralMethods {
public static void main(String[] args) {
if (args.length <= 1 || args.length > 2) {
println("Error, usage: software must get two input files");
System.exit(1);
}
String file_name1 = args[0]; // data to insert
String file_name2 = args[1]; // data to check
File data_to_insert = new File(file_name1);
File data_to_check = new File(file_name2);
Scanner input = new Scanner(System.in); // Create a Scanner object
println("Enter hashTable size");
int hashTable_size = input.nextInt(); // Read hashTable_size from user
println("Enter num of hashing function");
int num_of_has = input.nextInt(); // Read num of hashing from user
hashTable T = new hashTable(hashTable_size);
println("hashTable before insert values\n");
T.printHashTable();
input.close();
int i = 0;
try {
input = new Scanner(data_to_insert);
String data;
while ((data = input.next()) != null) {
T.set(i, Integer.parseInt(data));
i++;
}
input.close();
} catch (Exception e) {
System.out.println("\nError: Reading, An error occurred while reading input files. Check your input type");
e.printStackTrace();
}
T.printHashTable();
}
}
this is my output
Which prints the catch error
hashTable before insert values
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Error: Reading, An error occurred while reading input files. Check your input type
java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at main.main(main.java:36)
[1,2,3,4,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
In this line,
while ((data = input.next()) != null)
The next() method of Scanner does not return null if it has no more data, instead it throws the NoSuchElementException you are getting.
Use this instead to check for more data:
while ((input.hasNext()) {
data = input.next();
//...
}
Method hasNext() returns true or false as you would expect.

Java print specific data from file

I've a txt file. In there are rules and I have to get everything between the brackets in a separate file. But I don't even get it shown in the console.
I already tried many methods, but i always get some errors.(outlined code)
With the solution right now, it just showing nothing in the console. Does anyone know why?
The brackets are always in the same line as "InputParameters" i tried something with that, at the end of the code.
The solutions that are outlined won't work. Maybe someone got an idea?
with that code below i get the following error :
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1 at java.lang.String.substring(Unknown
Source) at blabla.execute.main(execute.java:17)
here some content from the txt file:
dialect "mvel"
rule "xxx"
when
InputParameters (xy <= 1.124214, xyz <= 4.214214, abc <= 1.12421, khg <= 1.21421)
then
Ty
Here is the code:
public class execute {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("C:..."));
java.lang.String line;
line = br.readLine();
while ((line = br.readLine()) != null) {
System.out.println(line.substring(line.indexOf(("\\("), line.indexOf(("\\)")))));
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1 at java.lang.String.substring(Unknown
Source) at blabla.execute.main(execute.java:17)
This exception means that -1 was passed to substring() method. This -1 is produced by indexOf() when it doesn't find anything.
Does all your lines contain brackets? There should be check if the brackets are present in the line.
while ((line = br.readLine()) != null) {
if(line.indexOf(("\\(") != -1 && line.indexOf(("\\)") != -1) {
System.out.println(line.substring(line.indexOf(("\\("), line.indexOf(("\\)")))));
}
}
the problem is if you want to get the index of a string (indexOf()) in a string in which the searched string doesnt exist, indexOf returns -1 and if the method substring receives the argument -1 then it throws a StringIndexOutOfBoundsException. I suggest to check first if a line contains "InputParameter" since you said this word is always in the same line and then you get the string inside the brackets by using the methods subtring and indexOf.
this one works for me
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileRead {
public static void main(String[] args) {
final String filename = "$insertPathToFile$";
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filename));
String line = br.readLine();
while(line != null){
if (line.contains("InputParameters")) {
System.out.println(line.substring(line.indexOf("(")+1, line.indexOf(")")));
} // end if
line = br.readLine();
} // end while
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
br.close();
} catch (IOException e) {}
} // end try
} // end main
} // end class

Want to know reason behind NumberFormat Exception in my code

I am trying to read file with BufferedReader and at the time of spliting each line of file I want to convert string data at 8th position to be converted to float.(count starts from 0 data)
below is my code :
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TestFloat {
static BufferedReader bin;
String line;
void sumAmount() throws IOException //Perform calculation
{
bin = new BufferedReader(new FileReader("D:\\Extras\\file.txt"));
//String firstline = bin.readLine();
while ((line = bin.readLine()) != null)
{
String data[] = line.split(",");
//System.out.println(data[8]);
System.out.println(Float.valueOf(data[8]));
//System.out.println(java.lang.Float.parseFloat(data[8]))
}
}
public static void main(String[] args)
{
TestFloat ts = new TestFloat();
try {
ts.sumAmount();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
for this code I am getting exception as below :
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
at java.lang.Float.parseFloat(Float.java:451)
at java.lang.Float.valueOf(Float.java:416)
at TestFloat.sumAmount(TestFloat.java:17)
at TestFloat.main(TestFloat.java:24)
one sample line of file.txt is :
20,20160518,262,20160518,00,F&O ABC DEBIT F 160518,000405107289,000405006220,5000000.00,5000000.00,0.00,,
I have tried with parseFloat and valueOf both function but it shows exception. What is the reason behind the fail?
java.lang.NumberFormatException: empty String
as the error states you're attempting to parse an empty string.
one solution is to use an if statement to guard off the NumberFormatException(only for empty strings that is, you could still get the NumberFormatException for unparseable strings).
if(data[8] != null && data[8].length() > 0){
System.out.println(Float.valueOf(data[8]));
System.out.println(java.lang.Float.parseFloat(data[8]));
}
you'll need to go through the debugger step by step and see what is the real issue behind it.

adding objects to java queues from a data file

I am trying to add objects to a queue from a data file which is made up of text which is made up of a person's first name and their 6 quiz grades (ie: Jimmy,100,100,100,100,100,100). I am accessing the data file using the FileReader and using BufferReader to read each line of my data file and then tokenize each line using the "," deliminator to divide the names and quiz grades up. Based on what I think my professor is asking for is to create a queue object for each student. The assignment says,
Read the contents of the text file one line at a time using a loop. In this loop, invoke the processInputData method for each line read. This method returns the corresponding Student object. Add this student object to the studentQueue.
If someone could point me the right direction that would be great! Here is my code so far:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) {
// Create an empty queue of student objects
LinkedList<Student> studentQueue;
studentQueue = new LinkedList<Student>();
// Create an empty map of Student objects
HashMap<String, Student> studentMap = new HashMap<String, Student>();
System.out.printf("Initial size = %d\n", studentMap.size());
// Open and read text file
String inputFileName = "data.txt";
FileReader fileReader = null;
// Create the FileReader object
try {
fileReader = new FileReader(inputFileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// BufferReader to read text file
BufferedReader reader = new BufferedReader(fileReader);
String input;
// Read one line at a time until end of file
try {
input = reader.readLine();
while (input != null) {
processInputData(input);
input = reader.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
// Close the input
try {
fileReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
// Tokenize the data using the "," as a delimiter
private static void processInputData(String data) {
StringTokenizer st = new StringTokenizer(data, ",");
String name = st.nextToken();
String homework1 = st.nextToken();
String homework2 = st.nextToken();
String homework3 = st.nextToken();
String homework4 = st.nextToken();
String homework5 = st.nextToken();
String homework6 = st.nextToken();
// Using the set methods to correspond to the Student object
Student currentStudent = new Student(name);
currentStudent.setHomework1(Integer.parseInt(homework1));
currentStudent.setHomework2(Integer.parseInt(homework2));
currentStudent.setHomework3(Integer.parseInt(homework3));
currentStudent.setHomework4(Integer.parseInt(homework4));
currentStudent.setHomework5(Integer.parseInt(homework5));
currentStudent.setHomework6(Integer.parseInt(homework6));
System.out.println("Input File Processing...");
System.out.println(currentStudent);
}
}
One possible solution to your problem is returning the student in processInputData(..)
private static Student processInputData(String data) {
// the same code
return currentStudent;
}
And in while loop
while (input != null) {
studentQueue.add(processInputData(input));
input = reader.readLine();
}
Also try to manage better your try-catch blocks, cause if your fileReader throws exception then the code will continue running and throw probably a nullPointerException that you don't handle.
try{
fileReader = new FileReader(inputFileName);
BufferedReader reader = new BufferedReader(fileReader);
}catch(IOException ex){
//handle exception;
}finally{
// close resources
}

Reading Strings from text files in java

im studying for my programming final exam. I have to write a program which opens a file which is stored in the string fileName and look in the file for a String called personName and this should print the first string after personName then the program should terminate after printing it,
if the argument personName is not in the file then it should print "this name doen't exsit" then if an IOException occurs it should then print "there is an IO Error" and the program should exsit using system.exit(0)
the program should use the file info.txt and each line should contain two strings
first string name and second age.
everything must be in one method
data.txt contains
Max 60.0
joe 19.0
ali 20.0
my code for this so far is :
public class Files{
public void InfoReader(String fileName, String personName)
{
try{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C://rest//data.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//Read File Line By Line
while ((fileName = br.readLine()) != null) {
// Print the content on the console
(new Files()).infoReader("info.txt","Joe"); //this prints the age
}
//Close the input stream
in.close();
}
catch (IOException e)
{//Catch exception if any
System.out.println(" there is an IO Error");
System.exit(0);
}
}
catch (Exception e)
{//Catch exception if any
System.out.println("that name doesn't exists");
}
}
}
infoReader(info.txt,Joe); should print 19.0
But I am getting a java.lang.StackOverflowError
any help would be much appreciated!!
Thanks in advance!
This is what I think you are trying to do. And if doesn't, at least can work as an example. Just as amit mentions, your current error is because of the recursive call, which I think is not necessary.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Files {
public void InfoReader(String fileName, String personName) {
try {
// Open the file that is the first command line parameter
FileInputStream fstream = new FileInputStream(fileName);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = null;
//Loop until there are no more lines in the file
while((line = br.readLine()) != null) {
//Split the line to get 'personaName' and 'age'.
String[] lineParts = line.split(" ");
//Compare this line personName with the one provided
if(lineParts[0].equals(personName)) {
//Print age
System.out.println(lineParts[1]);
br.close();
System.exit(0);
}
}
br.close();
//If we got here, it means that personName was not found in the file.
System.out.println("that name doesn't exists");
} catch (IOException e) {
System.out.println(" there is an IO Error");
}
}
}
If you use the Scanner class, it would make your life so much easier.
Scanner fileScanner = new Scanner (new File(fileName));
while(fileScanner.hasNextLine()
{
String line = fileScanner.nextLine();
Scanner lineScanner = new Scanner(line);
String name = lineScanner.next(); // gets the name
double age = Double.parseDouble(lineScanner.next()); // gets the age
// That's all really! Now do the rest!
}
Use commons-io and dont forget the encoding!
List<String> lines = FileUtils.readLines(file, encoding)

Categories