Problem with buffered File Reader - java

I have been asked to write a file reader method, I have done one which works fine but cant get the 2nd one to work and keep getting this error after i open the booms.txt file
Error:java.util.NoSuchElementException
public instance variable
public List booms;
Code I'm using for the file reader
try
{
int x;
int y;
double boomTime;
boolean isAHit;
Scanner lineScanner;
bufferedFileReader = new BufferedReader(new FileReader(aFile));
String currentLine = bufferedFileReader.readLine();
while (currentLine != null)
{
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter(",");
x = lineScanner.nextInt();
y = lineScanner.nextInt();
boomTime = lineScanner.nextDouble();
isAHit = lineScanner.nextBoolean();
booms.add(new Boom(x,y,boomTime));
currentLine = bufferedFileReader.readLine();
}
}
catch (Exception anException)
{
System.out.println("Error:"+anException);
}
finally
{
try
{
bufferedFileReader.close();
}
catch (Exception anException)
{
System.out.println("Error:" +anException);
}
}
}
Please Help

Perhaps a blank line at the end of the file?

as maurice says, probably a blank or incorrect line of data in the file.
the exception (although you haven't posted the stack trace) is being thrown by the Scanner.next... calls.
Scanner.nextInt
NoSuchElementException - if input is
exhausted
this would be far more obvious to you and the members of this forum if you'd included the stack trace. try putting anException.printStackTrace(); in your catch blocks next time.

I'm using a another method that's not that complicated. just do this:
Scanner diskScanner = new Scanner(new File("pathname"));
to read for example a Integer from the specified file just type
int blahblahblah = diskScanner.nextInt();

Got it sorted I had a boolean variable which wasn't in the file it was reading :), its all about taking a break and looking at it again.

Related

System.out.println() calls being ignored as well as an element not being added into an ArrayList?

I'm currently working on a program to read in info from a text file and output it on a spreadsheet using Apache's POI.
Let me show you what I have
ExcelFile ef = new ExcelFile(file, "the destination");
The constructor for the ExcelFileObject:
public ExcelFile(File file, String fp){
System.out.println("Entered ExcelFile constructor");
util = new ExcelUtilities();
this.filepath = fp;
this.data = util.readFromFile(file);
}
And then the readFromFile method:
public ArrayList<InputData> readFromFile(File file){
System.out.println("Entered readFromFile in ExcelUtilities");
ArrayList<InputData> data = new ArrayList<InputData>();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
while((line = br.readLine()) != null){
if(line.length() > 0){
System.out.println(line);
int x = Integer.parseInt(br.readLine());
System.out.println(x);
int y = Integer.parseInt(br.readLine());
System.out.println(y);
data.add(new InputData(line, x, y)); //Not adding the first thing read in for some odd reason.
}
}
br.close();
return data;
}catch (NumberFormatException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
The problem I ran into was that the first object from the .txt file formatted correctly was not being added to the ArrayList data. When I ran in the debugger (using Eclipse), I noticed that it was reading in the first line, x, and y values but never actually storing the object in data.
Then I ran into an even stranger problem. I added the System.out.println() statements as another level of verification that the data from the file was being read in properly, and they weren't even being printed onto the console! I tried running another project that contained println()'s and they worked fine.
So, I guess the main question is why isn't the first entree from the file being added the ArrayList? Followed by why aren't the println() calls being displayed on Eclipse's console?
The selected box in the output is where "Hello" should be placed.

How to use Constructor Scanner in java programming to grasp number of lines in text file

I was trying to remove the first line in text file using java code referencing from this link but still the scanner does not contain any text, so it write nothing in the text file, please help, what is then problem...?
here is a peace of code,
File path=new File("C:/Users/kassim Ismail/workspace/Coding/textdoc.txt");
Scanner scan=new Scanner(path);
FileWriter newread=new FileWriter("C:\\Users\\kassim Ismail\\workspace\\Coding\\textdoc.txt");
BufferedWriter newreader=new BufferedWriter(newread);
while(scan.hasNextLine()){
String nextline=scan.nextLine();
if(nextline.equals("\n")){
newreader.newLine();
}else{
newreader.write(nextline);
}
}
scan.close();
newreader.close();
newread.close();
}
Right now I don't see any mistake in your code (reader/writer should work). One thing I am unsure about is wether the blank space in your Filepath is problematic or not (Some programs can't work with blank spaces in file paths I am not sure about Java though).
Maybe you could add some System.out.println("") statements for debugging purposes. For Example (testing if the input file exists):
System.out.println("Inputfile exists: "+path.exists())
printing the read line:
System.out.println("Read line: "+nextline)
private boolean removeTopLine(File file){
try{
boolean status = false;
Scanner s = new Scanner(file);
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
String content = "";
int counter = 0;
while (s.hasNextLine()){
if (counter > 0){
content += s.nextLine();
}
counter++;
}
writer.write(content);
writer.close();
status = true;
}
catch (Exception e){
e.printStackTrace();
}
return status;
}
This is a functional code snippet that would delete the first line of a file however there could be debate on efficiency.

Java parseInteger throwing error

I have the following code snippet from my tester class.
FileReader freader=new FileReader(filename);
BufferedReader inputFile=new BufferedReader(freader);
int numScores = 0;
String playerType = "";
String nameHome = "";
String playerName = "";
String home = "";
String location = "";
int score = 0;
String date = "";
double courseRating = 0;
int courseSlope = 0;
ArrayList<Player> players = new ArrayList<Player>();
while (inputFile.read()!= -1) {
numScores = Integer.parseInt(inputFile.readLine());
playerType = inputFile.readLine();
nameHome = inputFile.readLine();
StringTokenizer st = new StringTokenizer(nameHome,",");
playerName = st.nextToken();
home = st.nextToken();
The program compiles, however when the tester is run, I get the following output error.
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at PlayerTest.main(PlayerTest.java:34)
I've tried researching this and what I fould was there's possibly a space when it changes the String that is read from the data file and converts it to an int. I tried reading directly into a strin, trimming the string, then converting to the int, but it got the same error.
This was the code that replaced numScores = Integer.parseInt(inputFile.readLine());
tempScores = inputFile.readLine();
tempScores.trim();
System.out.println(tempScores);
numScores = Integer.parseInt(tempScores);
Any help is appreciated.
*edited to show sample data
Sample data from file
3
B
James Smith, Strikers
FWB Bowling, 112,09/22/2012
White Sands, 142,09/24/2012
Cordova Lanes,203,09/24/2012
Possibly, your File contains empty lines. These are read as "" and therefore cannot be converted to int.
Furthermore, it is possible that you read the first character of each line by the read-statement in the header of the while-loop, so that it is ignored in the readline command. Then a number of length 1 (like "1") would become an empty line.
In any case, the construction of your loop is a bug.
You can put it all in an if statement:
if(!tempScores.equalsIgnoreCase(""))
{
I ran into a similar issue today. I was reading a response from REST end point and try to parse the json response. Bam! hit an error. Later on I realize the file had a BOM.
My suggestion is create a var
String var = inputFile.readLine();
int numScores = Integer.parseInt(var);
add a breakpoint and inspect what var contains, in my case the response had a BOM an empty unicode character code 65279 / 0xfeff. In any debugger worth it's salt you should be able to see each character.
if it's the case you need to strip that value from the string.
I used this library to detect this issue org.yaml:snakeyaml:1.16
import org.yaml.snakeyaml.reader.UnicodeReader;
//more code
private String readStream(InputStream inputStream) throws IOException {
UnicodeReader unicodeReader = new UnicodeReader(inputStream);
char[] charBuffer = new char[BUFFER_SIZE];
int read;
StringBuilder buffer = new StringBuilder(BUFFER_SIZE);
while ((read = unicodeReader.read(charBuffer,0,BUFFER_SIZE)) != -1) {
buffer.append(charBuffer, 0, read);
}
return buffer.toString();
}
You need to understand this please look into it.
Basic understanding is
try {
//Something that can throw an exception.
} catch (Exception e) {
// To do whatever when the exception is caught.
}
There is also an finally block which will always be execute even if there is an error. it is used like this
try {
//Something that can throw an exception.
} catch (Exception e) {
// To do whatever when the exception is caught & the returned.
} finally {
// This will always execute if there is an exception or no exception.
}
In your particular case you can have the following exceptions (link).
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
So you would need to catch exceptions like
try {
rows=scan.nextInt();
} catch (InputMismatchException e) {
// When the InputMismatchException is caught.
System.out.println("The next token does not match the Integer regular expression, or is out of range");
} catch (NoSuchElementException e) {
// When the NoSuchElementException is caught.
System.out.println("Input is exhausted");
} catch (IllegalStateException e) {
// When the IllegalStateException is caught.
System.out.println("Scanner is close");
}

Returning the number of lines in a .txt file

This is my debut question here, so I will try to be as clear as I can.
I have a sentences.txt file like this:
Galatasaray beat Juventus 1-0 last night.
I'm going to go wherever you never can find me.
Papaya is such a delicious thing to eat!
Damn lecturer never gives more than 70.
What's in your mind?
As obvious there are 5 sentences, and my objective is to write a listSize method that returns the number of sentences listed here.
public int listSize()
{
// the code is supposed to be here.
return sentence_total;}
All help is appreciated.
To read a file and count its lines, use a java.io.LineNumberReader, plugged on top of a FileReader. Call readLine() on it until it returns null, then getLineNumber() to know the last line number, and you're done !
Alternatively (Java 7+), you can use the NIO2 Files class to fully read the file at once into a List<String>, then return the size of that list.
BTW, I don't understand why your method takes that int as a parameter, it it's supposed to be the value to compute and return ?
Using LineNumberReader:
LineNumberReader reader = new LineNumberReader(new FileReader(new File("sentences.txt")));
reader.skip(Long.MAX_VALUE);
System.out.println(reader.getLineNumber() + 1); // +1 because line index starts at 0
reader.close();
use the following code to get number of lines in that file..
try {
File file = new File("filePath");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
int totalLines = 0;
while((line = reader.readLine()) != null) {
totalLines++;
}
reader.close();
System.out.println(totalLines);
} catch (Exception ex) {
ex.printStackTrace(System.err);
}
You could do:
Path file = Paths.getPath("route/to/myFile.txt");
int numLines = Files.readAllLlines(file).size();
If you want to limit them or process them lazily:
Path file = Paths.getPath("route/to/myFile.txt");
int numLines = Files.llines(file).limit(maxLines).collect(Collectors.counting...);

Read a single file with multiple BufferedReaders

I'm working on a program that needs to update a line that depends its value on the result of a line that goes read after. I thought that I could use two BufferedReaders in Java to position the reader on the line to update while the other one goes for the line that fixes the value (it can be an unknown number of lines ahead). The problem here is that I'm using two BufferedReaders on the same file and even if I think I'm doing right with the indexes the result in debug doesn't seem to be reliable.
Here's the code:
String outFinal
FileName=fileOut;
File fileDest=new File(outFinalFileName);
try {
fout = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(fileDest)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FileReader inputFile=null;
try {
inputFile = new FileReader(inFileName);
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}
BufferedReader fin = new BufferedReader(inputFile);
BufferedReader finChecker = new BufferedReader(inputFile); //Checks the file and matches record to change
String line="";
String lineC="";
int lineNumber=0;
String recordType="";
String statusCode="";
try {
while ((lineC = finChecker.readLine()) != null) {
lineNumber++;
if (lineNumber==1)
line=fin.readLine();
recordType=lineC.substring(0,3);//Gets current Record Type
if (recordType.equals("35")){
while(!line.equals(lineC)){
line=fin.readLine();
if (line==null)
break;
fout.write(line);
}
}else if (recordType.equals("32")){
statusCode=lineC.substring(4,7);
if(statusCode.equals("XX")){
updateRecordLine(line,fout);
}
}
}
returnVal=true;
} catch (IOException e) {
e.printStackTrace();
}
Thanks in advance.
Well, the BufferedReader only reads stuff, it doesn't have the ability to write data back out. So, what you would need is a BufferedReader to get stuff in, and a BufferedWriter that takes all the input from the BufferedReader, and outputs it to a temp file, with the corrected/appended data.
Then, when you're done (i.e. both BufferedReader and BufferedWriter streams are closed), you need to either discard the original file, or rename the temp file to the name of the original file.
You are basically copying the original file to a temp file, modifying the line in question in the temp file's output, and then copying/renaming the temp file over the original.
ok, i see some problem in your code exactly on these lines-->
recordType=lineC.substring(0,3);//Gets current Record Type
if (recordType.equals("35")){
if you see on the first line, you are getting the substring of recordType into recordType. Now recordType length is 3. If at all the recordType has only 2 characters, then substring throws arrayIndexOutOfBoundsException. So when no runtime exceptions, its length is 3 and on the next line you are calling the equals method that has a string with 2 characters.
Will this if block ever run ?

Categories