BufferedReader - count lines containing a string - java

I am using a .txt file that contains: "Hello world\nHow are you doing this day?" I want to count whether a line contains a string or not, as well as the total number of lines. I use:
File file = new File(file_Path);
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int i=0;
int j=0;
while ((line = br.readLine()) != null) {
j++;
if (line.contains("o")) { //<----------
i++;
}
}
System.out.print("Lines containing the string: " + i + " of total lines " + j-1);
As I run and test line.contains("o"), it prints 2 lines containing "o", which is correct as well as 2 total lines. As I run line.contains("world"), it prints 0 lines which is wrong but gives 2 lines total. But what do I do wrong?

I tested it with a StringReader,
String str = "Hello world\nHow are you doing this day?";
StringReader sr = new StringReader(str);
try {
BufferedReader br = new BufferedReader(sr);
String line;
int i = 0;
int j = 0;
while ((line = br.readLine()) != null) {
j++;
if (line.contains("world")) { // <----------
i++;
}
}
System.out
.println("Lines containing the string: " + i
+ " of total lines " + j);
} catch (Exception e) {
e.printStackTrace();
}
Your file contents must not be what you think because I get
Lines containing the string: 1 of total lines 2

As the others answers and comments, I also think you may not be reading the file you think you are... (Relax it happens to everyone from time to time)
But, also it could be the encoder of the file or the version of the jdk you have, maybe if you could answer:
What did you use to create the file?
What OS you are running
this?
What JDK are you using?
It could clarify what may have happened
Just for you to know, I ran the same code you have using jdk8 and worked fine for me.
As follows the test I did:
1) I put your code in a function:
int countLines(String filename, String wording) {
File file = new File(filename);
String line;
int rowsWithWord = 0;
int totalRows = 0;
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
while ((line = br.readLine()) != null) {
totalRows++;
if (line.contains(wording)) {
rowsWithWord++;
}
}
} catch (IOException e) {
System.out.println("Error Counting: " + e.getMessage());
}
System.out.println(String.format("Found %s rows in %s total rows", rowsWithWord, totalRows));
return rowsWithWord;
}
2) and ran the following unit test
#Test
public void testFile() {
try (FileWriter fileWriter = new FileWriter(new File("C:\\TEMP\\DELETE\\Hello.txt"));
BufferedWriter writer = new BufferedWriter(fileWriter)) {
writer.write("Hello world\nHow are you doing this day?");
} catch (IOException e) {
System.out.println("Error writing... " + e);
}
int countO = fileUtils.countLines("C:\\TEMP\\DELETE\\Hello.txt", "o");
Assert.assertEquals("It did not find 2 lines with the letters = o", 2, countO);
int countWorld = fileUtils.countLines("C:\\TEMP\\DELETE\\Hello.txt", "world");
Assert.assertEquals("It did not find 1 line with the word = world", 1, countWorld);
}
And I got the expected result:
Found 2 rows in 2 total rows
Found 1 rows in 2 total rows

Related

Editing a text File in Java and saving it as a new text file

I have a text file with 5 lines, I wish to read in those lines and be able to number them 1 - 5, and save them in a different file. The numbers begin before the start of the line. I have tried to hard code in a loop to read in the number but I keep getting errors.
public class TemplateLab5Bronze {
static final String INPUT_FILE = "testLab5Bronze.txt";
static final String OUTPUT_FILE = "outputLab5Bronze.txt";
public static void main(String[] args) {
try {
FileReader in = new FileReader(INPUT_FILE);
PrintWriter out = new PrintWriter(OUTPUT_FILE);
System.out.println("Working");
BufferedReader inFile = new BufferedReader(in);
PrintWriter outFile = new PrintWriter(out);
outFile.print("Does this print?\n");
String trial = "Tatot";
outFile.println(trial);
System.out.format("%d. This is the top line\n", (int) 1.);
System.out.format("%d. \n", (int) 2.);
System.out.format("%d. The previous one is blank.\n", (int) 3.);
System.out.format("%d. Short one\n", (int) 4.);
System.out.format("%d. This is the last one.\n", (int) 5.);
/*if(int j = 1; j < 6; j++){
outFile.print( i + trial);
}*/
String line;
do {
line = inFile.readLine();
if (line != null) {
}
} while (line != null);
inFile.close();
in.close();
outFile.close();
} catch (IOException e) {
System.out.println("Doesnt Work");
}
System.out.print("Done stuff!");
}
}
This is all the code I have so far, excluding the import statements, the commented for loop is what I was trying to use. Is there another way to do this?
One way to do it is to add to the printWriter while looping through the existing file:
FileReader fr = new FileReader("//your//path//to//lines.txt");
BufferedReader br = new BufferedReader(fr);
try (PrintWriter writer = new PrintWriter("//your//other//path//newlines.txt", "UTF-8")) {
String line;
int num = 1;
while ((line = br.readLine()) != null) {
writer.println(num + ". " + line);
num++;
}
}
Note: I didn't put in any catch statements, but you might want to catch some/all of the following: FileNotFoundException, UnsupportedEncodingException, IOException
You don't need two PrintWriters. Use only one.
PrintWriter outFile = new PrintWriter(OUTPUT_FILE);
You can simply use a counter instead of a for loop (which you have incorrectly written as if - as mentioned by #Shirkam)
String line;
int count=1;
do {
line = inFile.readLine();
if (line != null) {
outFile.println( count++ +"." + line);
}
} while (line != null);
inFile.close();
This works fine at my end.

How can i multiply all the numbers by 10 in java file I/O

Okay, so I have to Write a program to create a file named Lab13.txt. Write ten integers ranging [0, 99] created randomly into the file using text I/O. Integers are separated by spaces in the file. Read the data back from the file and display them on the console.
I've done this part already, but next I have to take those numbers in that file, create a new file, multiply all the numbers in the Lab13.txt file, and store them in the new file. My problem is when i create the new file, I'm only able to get it to multiply the last number printed from the Lab13.txt file. How do i get it to multiply all the numbers in Lab13.txt file by 10 and print them? This is probably a really simple solution and I feel so dumb for not being able to figure it out. Creating files is the new thing we're learning and my teacher is little to no help. :(
import java.io.*;
public class Lab13 {
public static void main(String ar[]) {
String toWrite = "";
int x=0;
try {
File file=new File("Lab13.txt");
FileWriter filewriter=new FileWriter(file);
BufferedWriter writer=new BufferedWriter(filewriter);
for(int i=0;i<10;i++) {
x=(int)(Math.random()*100);
writer.write(" "+x);
}
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
try {
File file1=new File("Lab13.txt");
FileReader filereader=new FileReader(file1);
BufferedReader reader=new BufferedReader(filereader);
String y;
while((y=reader.readLine())!=null) {
System.out.println(y);
toWrite += ("" + x*10);
System.out.println(toWrite);
}
File output = new File("lab13_scale.txt");
if(!output.exists()) output.createNewFile();
FileWriter writer = new FileWriter(output.getAbsoluteFile());
BufferedWriter bWriter= new BufferedWriter(writer);
bWriter.write(toWrite);
bWriter.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
You're never reading individual numbers from that line. And the x you multiplied with 10 was the last number you randomly generated in previous loop. That's why the problem.
Remove line -
toWrite += ("" + x*10);
Replace with -
String numArray = y.split(" ");
for (int i=0; i<numArray.length; i++) {
int newNum = Integer.parseInt(numArray[i]) * 10;
toWrite += ("" + newNum);
}
Your problem is here:
while((y=reader.readLine())!=null) {
System.out.println(y);
toWrite += ("" + x*10);
System.out.println(toWrite);
}
What reader.readLine() tells the reader to do is look for every newline character "\n" and process the chunks of text in between, and since you didnt add any, it treats the whole file as a single chunk.
What you can do instead is read the entire contents of the file into a string and then split it with the space delimiter (below is untested code):
String s = reader.readLine();
String[] allNumbers = s.split(" ");
for(String number : allNumbers) {
int currentNumber = Integer.parseInt(number);
bWriter.write(String.valueOf(currentNumber * 10) + " ");
}
public void multiply() throws Exception{
//reading from existing file
BufferedReader br = new BufferedReader(new FileReader("Lab13.txt"));
String l = br.readLine(); //assuming from your code that there is only one line
br.flush();
br.close();
String[] arr = l.split(" ");
//writing into new_file.txt
BufferedWriter bw = new BufferedWriter(new FileWriter("new_file.txt"));
for(String a : arr){
bw.write((Integer.parseInt(a)*10) + " ");
}
bw.flush();
bw.close();
}
Just call this method. Should work. You basically need to split the String using space. once that done, parsing each String into Integer and multiplying. and again storing.
package com.test;
import java.io.*;
public class Lab13
{
public static void main(String ar[])
{
String toWrite = "";
int x = 0;
try
{
File file = new File("Lab13.txt");
FileWriter filewriter = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(filewriter);
for (int i = 0; i < 10; i++)
{
x = (int) (Math.random() * 100);
writer.write(" " + x);
}
writer.close();
} catch (IOException e)
{
e.printStackTrace();
}
try
{
File file1 = new File("Lab13.txt");
FileReader filereader = new FileReader(file1);
BufferedReader reader = new BufferedReader(filereader);
String y;
while ((y = reader.readLine()) != null)
{
////////////////////////////////////////
//trim - delete leading spaces from y
String[] array = y.trim().split(" ");
for (int i = 0; i < array.length; i++)
{
int number = Integer.parseInt(array[i]);
System.out.println(number);
toWrite += (number * 10 + " ");
}
System.out.println(toWrite);
////////////////////////////////////////
}
File output = new File("lab13_scale.txt");
if (!output.exists()) output.createNewFile();
FileWriter writer = new FileWriter(output.getAbsoluteFile());
BufferedWriter bWriter = new BufferedWriter(writer);
bWriter.write(toWrite);
bWriter.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
}

program that uses input file and creates a new one

I'm writing a code that uses an input file called InvetoryReport.txt in a program I am supposed to create that is supposed to take this file, and then multiply two pieces of data within the file and then create a new file with this data. Also at the beginning of the program it is supposed to ask you for the name of the input file. You get three chances then it is to inform you that it cannot find it and will now exit, then stop executing.
My input file is this
Bill 40.95 10
Hammer 1.99 6
Screw 2.88 2
Milk .03 988
(The program is supposed to multiply the two numbers in the column and create a new column with the sum, and then under print another line like this
" Inventory Report
Bill 40.95 10 409.5
Hammer 1.99 6 11.94
Screw 2.88 2 5.76
Milk .03 988 29.64
Total INVENTORY value $ 456.84"
and my program I have so far is this
package textfiles;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.IOException;
public class LookOut{
double total = 0.0;
String getFileName(){
System.out.printIn("Type in file name here.");
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
out.println(str + "\n");
}
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
return str;
}
void updateTotal(double d){
total = total + d;
}
double getLineNumber(int String_line){
String [] invRep = line.split(" ");
Double x = double.parseDouble(invRep[1]);
Double y = double.parseDouble(invRep[2]);
return x * y;
}
void printNewData(String = newData) {
PrintWriter pW = new PrintWriter ("newData");
pw.print(newData);
pw.close;
}
public static void main(String[] args){
String str = ("Get file name");
String str = NewData("InventoryReport/n");
File file = new File(str);
Scanner s = new Scanner(file);
while(s.hasNextLine()) {
String line = s.nextLine();
double data = getLineNumber(line);
update total(data);
NewData += line + " " + data + "/n";
Print NewData(NewData);
}
}
}
I'm getting multiple error codes that I just cant seem to figure out.
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Despite your best intentions you are in fact missing a '}'. Note that you haven't escaped the Try block before the catch. I imagine this is because you confused the closing } for the while statement as the closing } for the try block. Do this instead:
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
}
}
catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Also, your indentation is ALL OVER THE PLACE. This should be a lesson to you in why you should format your code properly! It is so easy to miss simple syntax errors like that if you're not formatting properly. It's also hard for others to read your code and figure out what's wrong with it.

Count the amount of times a string appears in a file

I'm trying to figure out how I would read a file, and then count the amount of times a certain string appears.
This is what my file looks like, it's a .txt:
Test
Test
Test
Test
I want the method to then return how many times it is in the file. Any idea's on how I could go about doing this? I mainly need help with the first part. So if I was searching for the string "Test" I would want it to return 4.
Thanks in advanced! Hope I gave enough info!
Add this method to your class, pass your FileInputStream to it, and it should return the number of words in a file. Keep in mind, this is case sensitive.
public int countWord(String word, FileInputStream fis) {
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String readLine = "";
int count = 0;
while((readLine = in.readLine()) != null) {
String words = readLine.split(" ");
for(String s : words) {
if(s.equals(word)) count++;
}
return count;
}
Just wrote that now, and it's untested, so let me know if it works. Also, make sure that you understand what I did if this is a homework question.
Here you are:
public int countStringInFile(String stringToLookFor, String fileName){
int count = 0;
try{
FileInputStream fstream = new FileInputStream(fileName);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
int startIndex = strLine.indexOf(stringToLookFor);
while (startIndex != -1) {
count++;
startIndex = base.indexOf(stringToLookFor,
startIndex +stringToLookFor.length());
}
}
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
return count;
}
Usage: int count = countStringInFile("SomeWordToLookFor", "FileName");
If you have got to the point of reading in each file into a string I would suggest looking at the String method split.
Give it the string code 'Test' and it will return an array of type string - count the number of elements per line. Sum them up to get your total occurrence.
import java.io.*;
public class StringCount {
public static void main(String args[]) throws Exception{
String testString = "Test";
String filePath = "Test.txt";
String strLine;
int numRead=0;
try {
FileInputStream fstream = new FileInputStream(filePath);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((strLine = br.readLine()) != null) {
strLine = strLine + " ";
String [] strArry = strLine.split(testString);
if (strArry.length > 1) {
numRead = numRead + strArry.length - 1;
}
else {
if (strLine == testString) {
numRead++;
}
}
}
in.close();
System.out.println(testString + " was found " + numRead + " times.");
}catch (Exception e){
}
}
}
I would do this:
open and read the file line by line,
check how oft a line contains the given word...
increase a global counter for that..
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("Test.txt"));
Scanner sc = new Scanner(System.in);
System.out.print("Enter the subtring to look for: ");
String word = sc.next();
String line = in.readLine();
int count = 0;
do {
count += (line.length() - line.replace(word, "").length()) / word.length();
line = in.readLine();
} while (line != null);
System.out.print("There are " + count + " occurrences of " + word + " in ");
}

Buffered Output Writing to File Wrong

I can't figure it out. I'm trying to write out text from my program. It's suppose to a word count program. Show me the number of lines, characters, word count. Then I display the results along with the word the user is searching for and that line.
(i.e. searching java)
line 5: the island of java contains Java
line 9: I love to drink java
It's not displaying text. Its displaying like heiroglyphics.
Line 2: DN{c�<���\$H�Uz�X����h4[����bA.�D��Ja�8^)|��k�ˠ����<Τ���QJ�����P˒��nI"�(��vc�Bi�"&�/�|qI�W6{pa�0��[���[M��;�FU�!}4�x�����{�-��(����V�k#�We֭Tʺ
Line 3: �N�U �������Ӣ ͇�?�
Line 4: Ӻ鬵�P��D<�}L>��o�V�Ex���Q|�)�'��g�I�B�3b�(�"3�T�7��� �=��s�g�F�;KN���r��_�� ʺ:�� �B�ۢ�s��sP����[6��; �� PK ! ��� N _rels/.rels �(�
public void readFromFile(String filename)
{
LineNumberReader lineNumberReader = null;
try {
lineNumberReader = new LineNumberReader(new FileReader(filename));
String line = null;
BufferedWriter output = new BufferedWriter(new FileWriter("output.txt"));
String ask = "Enter Word";
String find = JOptionPane.showInputDialog(ask);
Scanner scan = new Scanner(new File("test.txt"));
while ((line = lineNumberReader.readLine()) != null)
{
line = scan.nextLine();
if(line.indexOf(find) >= -1)
{
output.write("Line " + lineNumberReader.getLineNumber() +
": " + line);
output.newLine();
}
}// end of while
output.close();
} // end of try
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally {
try {
if (lineNumberReader != null)
{
lineNumberReader.close();
}
} // end of try
catch (IOException ex)
{
ex.printStackTrace();
}
}// end of finally
} // end of function
I don't get why you are doing this :
while ((line = lineNumberReader.readLine()) != null)
{
line = scan.nextLine();
if(line.indexOf(find) >= -1)
{
output.write("Line " + lineNumberReader.getLineNumber() +
": " + line);
output.newLine();
}
}// end of while
instead of this :
while ((line = lineNumberReader.readLine()) != null)
{
if(line.indexOf(find) >= -1)
{
output.write("Line " + lineNumberReader.getLineNumber() +
": " + line);
output.newLine();
}
}// end of while
You don't need 2 readers for this. And I don't understand why one of the reader is reading in a final file and the other one is reading from a file which name is coming from arg
The default OS encoding is used as set in System.getProperty("file.encoding").
You can explicitly pick one.
final String encoding = "UTF-16LE"; // Or "Cp1252" or "UTF-8"
lineNumberReader = new LineNumberReader(new InputStreamReader(new FileInputStream(filename), encoding));
...
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt"), encoding));
...
Scanner scan = new Scanner(new File("test.txt", encoding));

Categories

Resources