Count number of lines that starts with & character in CSV file [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
BufferedReader is skipping every other line when reading my file in java
(3 answers)
Closed 2 years ago.
I am trying to make a function that will count how many lines starts with & in given file.
So far i came up with following function
public int CountNumberOfTexts(String filename) {
try{
File file = new File(filename);
if(file.exists()){
FileReader fr = new FileReader(file);
LineNumberReader lnr = new LineNumberReader(fr);
int linenumber = 0;
while (lnr.readLine() != null){
if (lnr.readLine().substring(0,1) == "&") {
linenumber++;
}
}
Log.d("Count", "NUMBER OF LINES: " + linenumber);
lnr.close();
return linenumber;
}else{
System.out.println("File does not exists: " + filename);
}
}catch(IOException e){
e.printStackTrace();
}
return 0;
}
Current Function error is: Not recognizing lines starting with & character.

You are facing two problems:
You are reading in two lines, but only evaluating every second:
while (lnr.readLine() != null){ <- first consumption
if (lnr.readLine().substring(0,1) == "&") { <- second
You are comparing strings with == operator instead of equals method. Or in your case you can even use startsWith method which is created precisely for scenarios like yours.
This will do the trick:
String line;
while ((line = lnr.readLine()) != null){
if (line.startsWith("&")) {

Related

Strange behavior reading files in Java [duplicate]

This question already has answers here:
BufferedReader is skipping every other line when reading my file in java
(3 answers)
Closed 4 months ago.
I'm trying to read nearly 120,000 lines from a file, put the data into a new record, and add this record to a list.
My problem is that I can't load all the data getting weird behavior.
In particular, using BufferedReader a first time I can count the rows and the result is correct, but when I try with a while loop to load the data into memory I see that the loop iterates about 60,000 times and the final list with the data contains only about 5000 objects.
I've also tried using other classes for loading data, but I always get the same problem.
I am currently using java 17 with spring and javafx.
Thank you.
I am attaching the latest version of my method:
public void getFixList(FixReadyCallback callback) {
List<Fix> fixList;
int firstCount = 0;
int whileCount = 0;
try {
File file = new File("src/main/resources/fligh_data/fix.dat");
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String currentLine = null;
while (reader.readLine() != null) {
firstCount++;
}
fixList = new ArrayList<>(firstCount);
reader.close();
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
while ((currentLine = reader.readLine()) != null) {
whileCount++;
currentLine = reader.readLine();
if (currentLine.matches(
"[-]?[0-9]{2}\\.[0-9]{6}\\s+[-]?[0-9]{3}\\.[0-9]{6}\\s+[0-9A-Z]{2,5}")) {
String[] splitted = currentLine.split("\\s+");
String denomination = splitted[2];
double latitude = Double.parseDouble(splitted[0]);
double longitude = Double.parseDouble(splitted[1]);
Coordinates coordinates = new Coordinates(latitude, longitude);
fixList.add(new Fix(denomination, coordinates));
}
}
System.out.println("FIRST_COUNT -> " + firstCount);
System.out.println("WHILE_COUNT -> " + whileCount);
System.out.println("LIST_SIZE -> " + fixList.size());
reader.close();
callback.onReady(fixList);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
And the output of the terminal:
FIRST_COUNT -> 119724
WHILE_COUNT -> 59862
LIST_SIZE -> 5128
while ((currentLine = reader.readLine()) != null) {
whileCount++;
currentLine = reader.readLine();
...
}
This skips every other line in your file. currentLine is already the next line in the file, and then you overwrite it with the line after that. I think you only meant to read one line per loop.
It seems pretty clear that you should simply delete the last line I quoted:
while ((currentLine = reader.readLine()) != null) {
whileCount++;
...
}

How to count characters 'A' or 'a' in a text file [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I need to create a program that will read in the contents of a .TXT file and output how many As’ (either A or a) that are present within the file.
Task: Start by downloading and importing the 7B_Batch.txt file into your project. Create a program that will read in the contents of this file and output how many As’ (either A or a) that are present within the file. There are a total of 250 lines in the file.
The file has these letters:
X
j
9
p
Q
0
n
v
[etc...]
And my code so far has been:
import java.io.*;
import java.util.*;
public class lettercount {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader ("7B_Batch.txt");
//connecting to file (7aname) by adding a file reader
BufferedReader br = new BufferedReader (fr);
//adding buffered reader which connects to the File Reader
int total = 0;
String line = br.readLine();
char find = 'A';
for ( int i = 0; i < 250; i++)
{
line = br.readLine();
if (line.equals(find))
{
total = total+1;
}
}
System.out.println("Counting the As' in the file....");
System.out.println("I found "+total +" As' in the file!");
}
}
The issue is that the line if (line.equals(find)) throws a NullPointerException:
Exception in thread "main" java.lang.NullPointerException at lettercount.main(lettercount.java:16)
You use br.readLine() before the loop, assigning it to the variable line. But you don't use that value because you overwrite this value at the beginning of the loop.
This way, you try to read lines of the file 251 times, although the loop runs 250 times. When trying to read the 251st line, there is none in the file and br.readLine() returns null.
Remove the call to br.readLine() when declaring the variable line.
An additional improvement would be to replace the for-loop with a while-loop that runs until br.readLine() returns null. This way, you don't have to know how many lines there are in the file beforehand.
You definitely need to check if line you've got from buffered reader is not null.
I think you have one additional read, which you don't need - before the loop you take the line, when you define the variable. That might lead to an NPE inside the loop.
I believe it doesn't make much sense to check whether String is equal to char as the result is always false.
According to the task you have to check both 'a' and 'A'.
Here is how I would solve this with java 8 streams, just replace ByteArrayInputStream with FileInputStream or create FileReader in-place.
ByteArrayInputStream in = new ByteArrayInputStream("a\nA\nb\nc\na\nd\n".getBytes());
try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
long count = reader.lines()
.filter(letter -> letter.compareToIgnoreCase("a") == 0)
.count();
System.out.println("There are " + count + " a's in the file");
}
Hope, this helps.
Well in order to avoid the null br.redLine() will get you a null when there are no more words so use a while for that, and in order to count what you need you can use Regex, Look this code I made hope it helps you (If you use Java 7 the code will be simpler), and i used a counter int so i know how manny aA are in the file
private static final String FILENAME = "/Users/jucepho/Desktop/ansi.txt";
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
String pattern = "[aA]";
Pattern r = Pattern.compile(pattern);
int counter=0;
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
br = new BufferedReader(new FileReader(FILENAME));
while ((sCurrentLine = br.readLine()) != null) {
//System.out.println(sCurrentLine);
Matcher m = r.matcher(sCurrentLine);
if (m.find( )) {
System.out.println(m.group());
counter++;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
System.out.println("There are :"+counter +" words");
}
It gives me as Result:
There are :218 words

How to count all lines with BufferedReader [duplicate]

This question already has answers here:
Java: How to read a text file
(9 answers)
Closed 6 years ago.
I just got stuck with this BufferedReader and I can't make it to read the whole txt file..it reads only the first line!
FileReader fr = new FileReader("/Users/esson/Desktop/sonnets/sonnet3.txt");
BufferedReader br = new BufferedReader(fr);
String input = br.readLine();
List<String> output= (List) Arrays.asList(input.split(" "));
for(String word: output) {
int times = Collections.frequency(output, word);
System.out.println("" + word+ " -- "+times);
and the output is:
When -- 1
most -- 1
I -- 1
wink -- 1
then -- 1
do -- 1
mine -- 1
eyes -- 1
best -- 1
see, -- 1
You need to put BufferedReader.readLine() in a loop. For example:
while((text = BufferedReader.readLine()) != null)
Also, I think you should tag the question as Java and not Javascript
int lineNum;
for(String word: output) {
lineNum++;
int times = Collections.frequency(output, word);
System.out.println("" + word+ " -- "+times);
}
System.out.println("Line Number is " + lineNum);

Problems with flush and printwriter [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I have the following code:
while (true) {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
String result = null;
while (result != "string") {
out.println("string one");
out.flush();
String var = null;
if ((var = in.readLine()) != null) {
var2 = function(login);
out.println(var2);
out.flush();
}
}
}
The flushing is not working correctly, mainly the first iteration of the outer while loop will print both outputs, but then after that there is an odd delay and everything is messed up ("string one" is not printing to the output).
What am I doing wrong?
You are using != tocompare String references which isn't going to do what you thinks, though it doesn't matter because you never change anyway.
Most likely you have a bug at the other end which is why readLine() blocks waiting for some text.

handling ArrayIndexOutOfBoundsException in java [duplicate]

This question already has answers here:
How can I avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException? [duplicate]
(2 answers)
Closed 7 years ago.
i have wrote the code to read a 3rd column of a file(treeout1.txt) and write those contents in another file(tree.txt).and now i want to open tree.txt and write the contents to stem.txt,where tree.txt contents a single word in each row and a delimiter is found at the end of each line.i have attached that txt file below.you can view that to have better understanding.now i want to write the words into a line till a delimiter "###" is found...for example 'the girl own paper' and next line vol and so on....i have tried that but ArrayIndexOutOfBoundsException comes for a[]...why?and how to resolve that?
the text file tree.txt is given below
the
girl
own
paper
###
vol
###
viii
###
no
###
#card#
###
October
#card#
#card#
###
price
one
penny
###
as
the
baron
have
conjecture
the
housemaid
whom
he
have
call
out
of
the
nursery
to
look
for
###
lons
cane
on
find
her
master
have
go
without
it
do
not
hurry
back
but
stop
talk
###
Code:
package simple;
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Simple {
public static void main(String[] args) throws IOException {
String line;
String line2;
String[] a = new String[100];
int i = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("C:/TreeTagger/treeout1.txt"));
BufferedWriter output = new BufferedWriter(new FileWriter("D:/tree.txt"));
String separator = System.getProperty("line.separator");
while ((line = br.readLine()) != null) {
StringTokenizer st2 = new StringTokenizer(line, "\n");
while (st2.hasMoreElements()) {
String line1 = (String) st2.nextElement();
String[] array = line1.split("\\s+", 3);
//System.out.println(array[2]);
output.append(array[2]);
output.newLine();
}
}
output.close();
br.close();
BufferedReader br1 = new BufferedReader(new FileReader("D:/tree.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("D:/stem.txt"));
while ((line2 = br1.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line2, " ");
while (st.hasMoreTokens()) {
String element = st.nextToken();
System.out.println(element);
while (element != "###") {
a[i] = element;
i++;
}
out.append(a[i]);
element = element.replace(element, "");
}
}
} catch (IOException e) {
}
}
}
You need to reset i to 0 after you find the ### delimiter. Otherwise you will keep incrementing i until it gets larger than 100 (a's maximum).
Also you can't use the != operator on Strings (from your code: element != "###"). You need to use the following:
!"###".equals(element);

Categories