How to count all lines with BufferedReader [duplicate] - java

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);

Related

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

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("&")) {

whole text file to string and count (nullpointerexception error) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
**
I want to get text from the user and find the number of words in the text according to the word searched. BufferedReader sets the readLine method to get all rows with while, but the program gives a null pointer exception error
.
The program worked fine when I used a single readline.
I think the problem is in the while loop but I do not understand the problem.**
Please Write Path : C:\Users\Soul Collector\Desktop\yazi okuma
Please Write the Name of Text : buffer
Text File :
hi hello my name is suat
hello there
Hello
Write the key word :
hi
Exception in thread "main" java.lang.NullPointerException
at project2.Count.SingleWord(Count.java:83)
at project2.Project2.main(Project2.java:45)
C:\Users\Soul Collector\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 18 seconds)
if(press == 2 )
{
System.out.print("Please Write Path : ");
scan.nextLine();
path = scan.nextLine();
System.out.print("Please Write the Name of Text : ");
txtname = "\\"+ scan.nextLine() + ".txt";
finalpath = path + txtname;
File dosya = new File(finalpath);
FileReader fr = new FileReader(dosya);
BufferedReader br = new BufferedReader(fr);
String dizi;
while((dizi = br.readLine()) != null){
System.out.println(dizi);
}
br.close();
/* StringTokenizer st = new StringTokenizer(dizi);
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}*/
String search=null;
System.out.println("Write the key word : ");
search = scan.nextLine();
Scanner s = new Scanner(dizi.toLowerCase());
while (s.hasNext()) {
toplamkelime++;
if (s.next().equals(search))
kelime ++;
}
System.out.println("Key Word : " + search);
System.out.println("Count of key word : " + kelime);
System.out.println("\n\n\n Total Count of Words : " + toplamkelime );
}
You are assigning value to 'dizi' within while conditions, so it was overwritten everytime. When there is something to read, 'dizi' has a value and get printed inside the while loop.
When nothing else to read 'dizi' is then has null value. So when you call 'dizi.toLowerCase()' later down the line, you get null pointer exception.
To fix the issue you need to keep track of all read dizi by using List or append them to another String.

Anyone understand external files well?

I am supposed to create a program that reads an external file with 3 integers on every line and find the area of a triangle with those three numbers. We haven't learned arrays yet though, so i want to create the program without an array, methods and classes are fine. I just need help reading the file every three numbers by line.
The data is:
7 8 9
9 9 12
6 5 21
24 7 25
13 12 5
50 40 30
10 10 10
82 34 48
4 5 6
Here's what i have so far:
import java.io.*;
import java.util.*;
import java.lang.*;
public class Prog610a
{
public static void main(String[] args) throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader("myData.in"));
String currentLine;
int a, b, c;
double s, area;
System.out.println("A" + "\t B" + "\t C" + "\t Area");
try
{
while((currentLine = reader.readLine()) != null)
{
Scanner scanner = new Scanner(currentLine);
s = ((scanner.nextInt() + scanner.nextInt() + scanner.nextInt()) / 2);
area = Math.sqrt(s * (s - scanner.nextInt()) * (s - scanner.nextInt()) * (s - scanner.nextInt()) );
if(s < 0)
{
System.out.println(scanner.nextInt() + " \t" + scanner.nextInt() +
" \t" + scanner.nextInt() + "\t This is not a triangle");
}
else
{
System.out.println(scanner.nextInt() + " \t" + scanner.nextInt() +
" \t" + scanner.nextInt() + " \t" + area);
}
}
}
finally
{
reader.close();
}
}
}
You have made a good start by using the Scanner. I would suggest that just using that may be insufficient, as you may end up with some malformed lines. To handle them you may wish to split the processing into two parts: get a line, and then get the individual values from that line.
That allows you to catch lines that do not have enough values, or have too many values. If you do not do this then you may become mis-aligned with the lines, reading some values from one line, and some from the following line.
The BufferedReader will allow you to read lines which you can then scan. Since you don't want to use arrays you must extract the numbers individually:
BufferedReader reader = new BufferedReader(new FileReader("myData.in"));
String currentLine;
try {
while ((currentLine = reader.readLine()) != null) {
Scanner scanner = new Scanner(currentLine);
try {
calculateTriangleArea(
scanner.nextInt(), scanner.nextInt(), scanner.nextInt()
);
}
catch (NoSuchElementException e) {
// invalid line
}
}
}
finally {
reader.close();
}
Also it may help you to understand the Java string interpolation. You have horizontalTab throughout your code. You can express that in a string by just using \t. For example:
"\tThis is indented by one tab"
"This is not"
You can find the complete list of string escape characters here.
The exception handling (or lack of) in my code may surprise you. In your code you catch the Exception that could be thrown. However you discard it and then proceed to execute the rest of the code on a Scanner that is known to be broken. In such a situation it is better to fail immediately rather than conceal the error and attempt to proceed.
The one bit of exception handling that does occur in my code is the finally block. This ensures that the reader is closed no matter what happens when reading from it. It wraps the code that is executed after the reader has been opened, and as such it is known that the reader is not null and should be closed after use.

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);

Java Array parsing

I have read a file into an array but am wondering how to parse certain values from that array.
My code:
...
try{
...
String strLine;
String delims= "[ ]+";
//parsing it
ArrayList parsedit = new ArrayList();
while((strLine=br.readLine())!=null){
System.out.println("Being read:");
System.out.println(strLine);
parsedit.add(strLine.split(delims));
}
System.out.println("Length:" + parsedit.size());
in.close();
...
The files that I am reading in are like this:
a b c d e f g
1 2 3 4 5 6 7
1 4 5 6 3 5 7
1 4 6 7 3 2 5
Which makes the output like this:
How many files will be input? 1
Hey, please write the full path of the input file number1!
/home/User/Da/HA/file.doc
Being read:
a b c d e f g
Being read:
1 2 3 4 5 6 7
...
Length:4
I would like to parse out this data and just have the first and fifth values remaining, so that it would read like this instead:
a e
1 5
Does anyone have a recommendation on how to go about it?
EDIT:
Following some of the suggestions I have changed my code to:
public static void main(String[] args) {
System.out.print("How many files will be input? ");
Scanner readIn=new Scanner(System.in);
int input=readIn.nextInt();
int i=1;
while(i<=input){
System.out.println("Hey, please write the full path of the input file number" + i + "! ");
Scanner fIn=new Scanner(System.in);
String fileinput=fIn.nextLine();
try{
FileInputStream fstream=new FileInputStream(fileinput);
DataInputStream in=new DataInputStream(fstream);
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String strLine;
String delims= "[ ]+";
ArrayList parsedit = new ArrayList();
while((strLine=br.readLine())!=null){
System.out.println("Being read:");
System.out.println(strLine);
parsedit.add(strLine.split(delims));
}
String[] splits=strLine.split(delims);
System.out.println("Length:" + splits.length);
in.close();
}
catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
i++;
}
}
}
This doesn't give back any errors but it doesn't seem to be working all the same. Am I missing something silly? The output is this:
How many files will be input? 1
Hey, please write the full path of the input file number1!
/home/User/Da/HA/file.doc
Being read:
a b c d e f g
Being read:
1 2 3 4 5 6 7
...
But despite the fact that I have a line to tell me the array length, it never gets printed, which tells me I just ended up breaking more than I fixed. Do you know what it is that I may be missing/forgetting?
The split() function returns an array of strings representing the tokens obtained from the original String.
So, what you want is to keep only the first and the 5th token (splits[0] & splits[4]):
String[] splits = strLine.split(delims);
//use the splits[0] & splits[4] to create the Strings you want
Regarding your update, replace this:
while((strLine=br.readLine())!=null){
System.out.println("Being read:");
System.out.println(strLine);
parsedit.add(strLine.split(delims));
}
With this:
while((strLine=br.readLine())!=null){
System.out.println("Being read:");
String splits[] = strLine.split(delims);
System.out.println(splits[0]+" "+splits[4]);
parsedit.add(splits);
}
You can try this
String[] line = s.split("\\s+");
This way all your elements will be stored in a sequence in the array line.
This will allow you to access whatever element you want.
You just need to get the first and the fifth value out of the String[] returned by strLine.split(delims).
(I am assuming you know what you are doing in your current code. You are assuming that each line will contains the same number of "columns", delimited by at least 1 space character. It is a fair assumption, regardless.)

Categories