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 ");
}
Related
I have a text file from which i am trying to search for a String which has multiple lines. A single string i am able to search but i need multi line string to be searched.
I have tried to search for single line which is working fine.
public static void main(String[] args) throws IOException
{
File f1=new File("D:\\Test\\test.txt");
String[] words=null;
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
String s;
String input="line one";
// here i want to search for multilines as single string like
// String input ="line one"+
// "line two";
int count=0;
while((s=br.readLine())!=null)
{
words=s.split("\n");
for (String word : words)
{
if (word.equals(input))
{
count++;
}
}
}
if(count!=0)
{
System.out.println("The given String "+input+ " is present for "+count+ " times ");
}
else
{
System.out.println("The given word is not present in the file");
}
fr.close();
}
And below are the file contents.
line one
line two
line three
line four
Use the StringBuilder for that, read every line from file and append them to StringBuilder with lineSeparator
StringBuilder lineInFile = new StringBuilder();
while((s=br.readLine()) != null){
lineInFile.append(s).append(System.lineSeparator());
}
Now check the searchString in lineInFile by using contains
StringBuilder searchString = new StringBuilder();
builder1.append("line one");
builder1.append(System.lineSeparator());
builder1.append("line two");
System.out.println(lineInFile.toString().contains(searchString));
More complicated solution from default C (code is based on code from book «The C programming language» )
final String searchFor = "Ich reiß der Puppe den Kopf ab\n" +
"Ja, ich reiß' ich der Puppe den Kopf ab";
int found = 0;
try {
String fileContent = new String(Files.readAllBytes(
new File("puppe-text").toPath()
));
int i, j, k;
for (i = 0; i < fileContent.length(); i++) {
for (k = i, j = 0; (fileContent.charAt(k++) == searchFor.charAt(j++)) && (j < searchFor.length());) {
// nothig
}
if (j == searchFor.length()) {
++found;
}
}
} catch (IOException ignore) {}
System.out.println(found);
Why don't you just normalize all the lines in the file to one string variable and then just count the number of occurrences of the input in the file. I have used Regex to count the occurrences but can be done in any custom way you find suitable.
public static void main(String[] args) throws IOException
{
File f1=new File("test.txt");
String[] words=null;
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
String s;
String input="line one line two";
// here i want to search for multilines as single string like
// String input ="line one"+
// "line two";
int count=0;
String fileStr = "";
while((s=br.readLine())!=null)
{
// Normalizing the whole file to be stored in one single variable
fileStr += s + " ";
}
// Now count the occurences
Pattern p = Pattern.compile(input);
Matcher m = p.matcher(fileStr);
while (m.find()) {
count++;
}
System.out.println(count);
fr.close();
}
Use StringBuilder class for efficient string concatenation.
Try with Scanner.findWithinHorizon()
String pathToFile = "/home/user/lines.txt";
String s1 = "line two";
String s2 = "line three";
String pattern = String.join(System.lineSeparator(), s1, s2);
int count = 0;
try (Scanner scanner = new Scanner(new FileInputStream(pathToFile))) {
while (scanner.hasNext()) {
String withinHorizon = scanner.findWithinHorizon(pattern, pattern.length());
if (withinHorizon != null) {
count++;
} else {
scanner.nextLine();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(count);
Try This,
public static void main(String[] args) throws IOException {
File f1 = new File("./src/test/test.txt");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
String input = "line one";
int count = 0;
String line;
while ((line = br.readLine()) != null) {
if (line.contains(input)) {
count++;
}
}
if (count != 0) {
System.out.println("The given String " + input + " is present for " + count + " times ");
} else {
System.out.println("The given word is not present in the file");
}
fr.close();
}
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.
I'm going to elabortate my question because I had a hard time labeling the question the right way.
I'm labeling my methods like this:
/*Start*/
public void contadorDeLineas(File file)throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
/*Finish*/
I have several methods labeled like that but I want to count them separately, but the code I wrote counts the lines inside the methods starting from public and finishing in "Finish". But as for now the code I wrote counts all the lines inside the methods and return the sum of all the lines. What I want to do is read the first block return that value and continue searching for the next block of code.
This is the code I wrote
public void LinesMethods(File file)throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int lines_inside = 0;
while((line = br.readLine())!=null){
if(line.startsWith("/*St")){
do{
line = br.readLine();
line = line.trim();
System.out.println(line);
if(!(line.equals("") || line.startsWith("/*"))){
lines_inside++;
}
}while(!line.startsWith("/*Fi"));
}
}
br.close();
System.out.println("Found: " + lines_inside);
}
This is an example of what my code is showing in the console
/*Start*/
public void LineMethods(File file)throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
/*Finish*/
/*Start*/
public static void main(String[] args)throws IOException{
program2 test = new program2();
File root = new File(args[0]);
test.LOC(root);
System.out.println("Found: " + test.lines);
System.out.println("Other type of lines: " + test.toDo);
}
}
/*Finish*/
Block comments lines: 11
Instead I'm looking for a result like a first print showing the number 3 and then a number 8.
Any guidance will be appreciated.
Try this
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
boolean inside = false;
int count = 0;
String line;
while ((line = br.readLine()) != null) {
if (line.contains("/*Start*/")) {
inside = true;
count = 0;
} else if (line.contains("/*Finish*/")) {
System.out.println("Found: " + count);
inside = false;
} else if (inside) {
++count;
}
}
if (inside && count > 0)
System.out.println("Found: " + count);
}
if you have several methods printing out all the lines may be to much when you are only interested in the number of lines. You can put the names of the methods and the number of lines in a map and print that out.
public static void LinesMethods(File file)throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int lines_inside = 0;
Map<String, Integer> map = new HashMap<>();
while((line = br.readLine())!=null){
lines_inside = 0;
if(line.startsWith("/*St")){
String method = "";
do{
line = br.readLine();
if(line.contains("public")){
method = line.substring(0, ine.indexOf('('));
}
line = line.trim();
if(!(line.equals("") || line.startsWith("/*"))){
lines_inside++;
}
}while(!line.startsWith("/*Fi"));
map.put(method, lines_inside);
}
}
br.close();
for(String s :map.keySet()){
System.out.println(s +" : "+ map.get(s));
}
}
Try to put lines_inside++; in the code like this:
while((line = br.readLine())!=null){
lines_inside++;
...
This gives you the rught number of elements in file.
I want to write small java program to read data file first field and add seqcution number
Input file:
robert,190 vikign,...
robert,2401 windy,...
robert,1555 oakbrook,...
michell,2524 sprint,...
michell,1245 oakbrrok,...
xyz,2455 xyz drive,....
Output file should be:
robert,190 vikign,...,0
robert,2401 windy,...,1
robert,1555 oakbrook,...,2
michell,2524 sprint,...,0
michell,1245 oakbrrok,...,1
xyz,2455 xyz drive,....,0
Check first field when value change sequction number start back to 0 otherwise add sequction number by 1
here is my code:
public static void createseq(String str) {
try {
BufferedReader br = null;
BufferedWriter bfAllBWP = null;
File folderall = new File("Sort_Data_File_Out");
File[] BFFileall = folderall.listFiles();
for (File file : BFFileall) {
br = new BufferedReader(new FileReader(file));
String bwp = "FinalDataFileOut\\" + str;
bfAllBWP = new BufferedWriter(new FileWriter(bwp));
String line;
line = br.readLine();
String[] actionID = line.split("\\|");
String fullname = actionID[0].trim();
int seq = 0;
String fullnameb;
while ((line = br.readLine()) != null) {
actionID = line.split("\\|");
fullnameb = actionID[0].trim();
if(fullname.equals(fullnameb)) {
seq++;
}
else {
System.out.println(line + "======" + seq + "\n");
seq = 0;
fullname = fullnameb;
}
System.out.println("dshgfsdj "+line + "======" + seq + "\n");
}
}
}
catch(Exception letterproof) {
letterproof.printStackTrace();
}
}
The below code will fix the issue.I have updated the code if you face any pblm plz let me know :
Input :
robert,190 vikign,...
robert,2401 windy,...
robert,1555 oakbrook,...
michell,2524 sprint,...
michell,1245 oakbrrok,...
xyz,2455 xyz drive,....
Code :
public static void createseq() {
try {
File file = new File("d:\\words.txt"); //Hardcoded file for testing locally
BufferedReader br = new BufferedReader(new FileReader(file));
HashMap<String,Integer> counter = new HashMap<String, Integer>();
String line;
while((line = br.readLine())!= null)
{
String[] actionID = line.split(",");
String firstName = actionID[0];
if(counter.containsKey(firstName))
{
counter.put(firstName, counter.get(firstName) + 1);
}
else
{
counter.put(firstName,0);
}
System.out.println(line+" "+counter.get(firstName));
}
br.close();
} catch(Exception letterproof) {
letterproof.printStackTrace();
}
}
Ouput Come :
robert,190 vikign,... 0
robert,2401 windy,... 1
robert,1555 oakbrook,... 2
michell,2524 sprint,... 0
michell,1245 oakbrrok,... 1
xyz,2455 xyz drive,.... 0
I have a .txt file with the following content:
1 1111 47
2 2222 92
3 3333 81
I would like to read line-by-line and store each word into different variables.
For example: When I read the first line "1 1111 47", I would like store the first word "1" into var_1, "1111" into var_2, and "47" into var_3. Then, when it goes to the next line, the values should be stored into the same var_1, var_2 and var_3 variables respectively.
My initial approach is as follows:
import java.io.*;
class ReadFromFile
{
public static void main(String[] args) throws IOException
{
int i;
FileInputStream fin;
try
{
fin = new FileInputStream(args[0]);
}
catch(FileNotFoundException fex)
{
System.out.println("File not found");
return;
}
do
{
i = fin.read();
if(i != -1)
System.out.print((char) i);
} while(i != -1);
fin.close();
}
}
Kindly give me your suggestions. Thank You
public static void main(String[] args) throws IOException {
File file = new File("/path/to/InputFile");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
while( (line = br.readLine())!= null ){
// \\s+ means any number of whitespaces between tokens
String [] tokens = line.split("\\s+");
String var_1 = tokens[0];
String var_2 = tokens[1];
String var_3 = tokens[2];
}
}
try {
BufferedReader fr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "ASCII"));
while(true)
{
String line = fr.readLine();
if(line==null)
break;
String[] words = line.split(" ");//those are your words
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
Hope this Helps!
Check out BufferedReader for reading lines. You'll have to explode the line afterwards using something like StringTokenizer or String's split.
import java.io.*;
import java.util.Scanner;
class Example {
public static void main(String[] args) throws Exception {
File f = new File("main.txt");
StringBuffer txt = new StringBuffer();
FileOutputStream fos = new FileOutputStream(f);
for (int i = 0; i < args.length; i++) {
txt.append(args[i] + " ");
}
fos.write(txt.toString().getBytes());
fos.close();
FileInputStream fis = new FileInputStream("main.txt");
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
String result = new String();
StringBuffer txt1 = new StringBuffer();
StringBuffer txt2 = new StringBuffer();
File f1 = new File("even.txt");
FileOutputStream fos1 = new FileOutputStream(f1);
File f2 = new File("odd.txt");
FileOutputStream fos2 = new FileOutputStream(f2);
while ((data = br.readLine()) != null) {
result = result.concat(data);
String[] words = data.split(" ");
for (int j = 0; j < words.length; j++) {
if (j % 2 == 0) {
System.out.println(words[j]);
txt1.append(words[j] + " ");
} else {
System.out.println(words[j]);
txt2.append(words[j] + " ");
}
}
}
fos1.write(txt1.toString().getBytes());
fos1.close();
fos2.write(txt2.toString().getBytes());
fos2.close();
br.close();
}
}