I am fairly new to Java and coding in general. In the below program, this is set to read the number of lines in a file and the number of characters.
While it gives the correct number of lines, I get more characters than present in my .txt file, so i assume it is also reading the new line characters. As an example, in a test file with the text: "hello world" it will read the character count as 12 instead of 10.
Any advice on how I would get my program to read only the characters and not the new line character also?
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JOptionPane;
public class ReadFile
{
public static void main(String[] args)
{
try { /*define block of code to test for errors while it is being executed*/
String inName = JOptionPane.showInputDialog("Please enter the input file name here");
int linecount = 0, charcount = 0;
/*open the input file*/
BufferedReader inBuf = new BufferedReader (new FileReader (inName)); /*Initializes buffered reader*/
while ((inBuf.readLine()) !=null) { /*reads the contents of the file, line by line*/
linecount++; /*counts the number of lines read*/
}
inBuf.close(); /*closes input file*/
BufferedReader inBuf2 = new BufferedReader (new FileReader (inName));
while ((inBuf2.read()) != -1) {
charcount++; /*counts the number of characters read*/
}
/*closes input file*/
inBuf2.close();
/*Displays the number of lines and characters read*/
JOptionPane.showMessageDialog(null, "Number of lines in this file is: " + linecount);
JOptionPane.showMessageDialog(null, "Number of characters in this file is: " + charcount);
}
/*catch that allows code to be executed if error occurs*/
catch (FileNotFoundException f) {
JOptionPane.showMessageDialog(null, "File cannot be found! Details:\n" + f);
}
catch (IOException a) {
JOptionPane.showMessageDialog(null, "An error has occured when reading this file! Details:\n" + a);
}
System.exit(0); /*exits system*/
}
}