I am trying to search a string in a file in java and this is what, I tried . In the below program I am getting output as No Data Found and I am sure that the file has the word which I am searching
import java.io.*;
import java.util.Scanner;
public class readfile {
static String[] list;
static String sear = "CREATE";
public void search() {
Scanner scannedFile = new Scanner("file.txt");
while (scannedFile.hasNext()) {
String search = scannedFile.next();
System.out.println("SEARCH CONTENT:"+search);
if (search.equalsIgnoreCase(sear)) {
System.out.println("Found: " +search);
}
else {
System.out.println("No data found.");
}
}
}
public static void main (String [] args) throws IOException {
readfile read = new readfile();
read.search();
}
}
Don't do:
search.equalsIgnoreCase(sear)
Try:
search.toUpperCase().contains(sear)
I think the search is the whole String of the File, so you never would become true with equals.
Use nextLine() instead of next() and then use split. Like this :
What's the difference between next() and nextLine() methods from Scanner class?
Difference :
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
Use following code :
String search = scannedFile.nextLine();
String[] pieces = data.split("\\s+");
for(int i=0; i<pieces.length(); i++)
{
if(pieces[i].equalsIgnoreCase(sear))
{
System.out.println("Found: " +search);
}
else
{
System.out.println("No data found.");
}
}
Ok, here is my understanding of your program.
You search in the file file.txt the word CREATE.
To do so, you read each word in the file and if it is CREATE you print Found create.
The issue here is that for every word in the file, if it isn't CREATE you print No data found.
Instead you should wait for the end of the file and then if you haven't found it you will print the error message.
Try this :
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class readfile {
static String[] list;
static String sear = "CREATE";
public void search() throws IOException {
List<String> saveAllLinesForRewriting = new ArrayList<String>();
// Need to read file line by line
BufferedReader bufferedReader = new BufferedReader(new FileReader("file.txt"));
String saveLine;
while ((saveLine = bufferedReader.readLine()) != null) {
saveAllLinesForRewriting.add(saveLine);
}
bufferedReader.close();
// Check if your word exists
if (saveAllLinesForRewriting.toString().contains(sear)) {
System.out.println("Found: " + sear);
} else {
System.out.println("No data found.");
}
}
public static void main(String[] args) throws IOException {
readfile read = new readfile();
read.search();
}
}
Instead of reading file using scanner, first create a file resource to read by adding the below line
File file = new File("Full Path of file location");
before
Scannner scannedfile = new Scanner("file.txt");
and change the above line to
Scanner scannedfile = new Scanner(file);
rest your code is working fine.
The problem is that the scanner is scanning the String "file.txt" and not the file.
To fix this you have to do what amit28 says. Your finally code is as follows
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class readfile {
static String[] list;
static String sear = "CREATE";
public void search() {
File f = new File("file.txt");
Scanner scannedFile;
try {
scannedFile = new Scanner(f);
while (scannedFile.hasNext()) {
String search = scannedFile.next();
System.out.println("SEARCH CONTENT:"+search);
if (search.equalsIgnoreCase(sear)) {
System.out.println("Found: " +search);
}
else {
System.out.println("No data found.");
}
}
} catch (FileNotFoundException e) {
// FIXME Auto-generated catch block
e.printStackTrace();
}
}
public static void main (String [] args) throws IOException {
readfile read = new readfile();
read.search();
}
}
Related
My target is to write a code which allow me to calculate number of lines in txt files from folder and his subfolders, i wrote a code which allows me to do it only for a single file, what should i change to get good result? Directory cant be specified in code.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Lines {
public static String getValueFromUser(String comment) {
Scanner scanner = new Scanner(System.in);
System.out.println(comment);
return scanner.nextLine();
}
public static void main(String[] args) {
String filePath = getValueFromUser("location: ");
readFileContent(filePath);
}
private static void readFileContent(String filePath) {
int numberOfLines = 0;
String textLine;
try (BufferedReader fileReader = new BufferedReader(new FileReader(filePath))) {
while ((textLine = fileReader.readLine()) != null) {
numberOfLines++;
}
System.out.println("number of lines: " + numberOfLines);
} catch (FileNotFoundException ex) {
System.out.println("no file found.");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
To count all lines of all .txt files in a directory you'd need to iterate over the content of that directory and its subdirectories. Using the Files class this is quite easy (if you're allowed to do so):
Files.walk(Path.of(filePath )) //iterates through all files and directories in the given locaction
.filter(path -> Files.isRegularFile(path)) //we're only interested in files
.filter(path -> path.toFile().getName().endsWith(".txt")) //specifically those ending in .txt
.forEach(path -> readFileContent(path.toString())); //call your method here
Note that this will just print the number of lines for each file. If you need to get a total you should not use forEach() but maptoInt(...).sum() and return the number of lines from your method.
I'm having trouble properly getting one line of text at a time from a file onto a queue without taking the whole file into the queue. For example, I'd like only Write a program that reads a Java source file as an argument and produces an index of all identifiers in the file. For each identifier, print all lines in which it occurs. For simplicity, we will consider each string consisting only of letters, numbers, and underscores an identifier.
Declare a Scanner in for reading from the source file and call in.useDelimiter("[^A-Za-z0-9_]+") Then each call to next returns an identifier.
public class Main { to get added to the queue but instead the whole file text is put into the queue instead of a line at a time. Sorry if my question is unclear
// Write a program that reads a Java source file as an argument and produces an index of all
// identifiers in the file. For each identifier, print all lines in which it occurs. For simplicity,
// we will consider each string consisting only of letters, numbers, and underscores an identifier.
// Declare a Scanner in for reading from the source file and call in.useDelimiter("[^A-Za-z0-9_]+").
// Then each call to next returns an identifier.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class E_15 {
public static void main(String[] args) throws FileNotFoundException
{
// get scanner input from file
Scanner fileInput = new Scanner(new File ("C:/Users/ramir/IdeaProjects/PA_7/src/Main.java"));
Queue<String> test = new LinkedList<String>();
ArrayList<String> phrase = new ArrayList<String>();
/*
List<String> result = new ArrayList<String>();
Scanner s = new Scanner(is);
s.useDelimiter(delimiter);
*/
// Iterates till end of file
while (fileInput.hasNextLine())
{
// Here is the issue. Data will end up
// containing the whole file instead of only that line
String data = fileInput.nextLine();
Scanner in = new Scanner(data);
in.useDelimiter("[^A-Za-z0-9_]+");
// I believe around here or before is the issue that I'm having.
// It adds all the file instead of only that line
// Also trying to figure out how to display each line that it's displayed on
// What the first one should look like for example
// 0: public occurs in:
// public class Main {
// public static void main(String[] args) {
//System.out.println(data);
test.add(data);
while(in.hasNext())
{
// Getting each phrase/word into ArrayList
String token = in.next();
phrase.add(token);
}
in.close();
}
int index = 0;
// This part works fine
for(String num : phrase)
{
// printing the key
System.out.println(index + ": " + num + " occurs in:");
// printing the values
// This to print out what
for(String line : test)
{
System.out.println(line);
}
System.out.println();
++index;
}
}
}
// Just java class get file front
// This is fine
public class Main {
public static void main(String[] args) {
int a_1 = 100;
System.out.println(a_1);``
}
}
I'd like it to only show System.out.println(a_1) because the line that's it's on See This
. I'm also have trouble printing it in all the lines that occur.
import java.io.*;
import java.util.Scanner;
public class ReadLineByLineExample2
{
public static void main(String args[])
{
try
{
//the file to be opened for reading
FileInputStream fis=new FileInputStream("Demo.txt");
Scanner sc=new Scanner(fis); //file to be scanned
//returns true if there is another line to read
while(sc.hasNextLine())
{
System.out.println(sc.nextLine()); //returns the line that was skipped
}
sc.close(); //closes the scanner
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Try studying the above code. I hope it will help. Otherwise, you might need to open this link for more detail.
Im currently trying to write a program that counts the amounts of times different words are being used in a text, and then attach the values to a hashmap. In the main part of the program i use a scanner to read in the file with the text, and i initiate the GenWordCtr with another scanner thats supposed to read in a file with words i want excluded (words like "this, her, that"). Ive made sure that the string sent to op.process is lowercased, however when i run the program it still adds all the values that i want excluded from the statistics. What am i doing wrong? I know the main program works, ive tried it with single words.
TLDR - i want words excluded using a scanner to read in a text, for some reason they arent being excluded in the "process" operation of my program.
package textproc;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Holgersson {
public static final String[] REGIONS = { "blekinge", "bohuslän", "dalarna", "dalsland", "gotland", "gästrikland",
"halland", "hälsingland", "härjedalen", "jämtland", "lappland", "medelpad", "närke", "skåne", "småland",
"södermanland", "uppland", "värmland", "västerbotten", "västergötland", "västmanland", "ångermanland",
"öland", "östergötland" };
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("../lab1/nilsholg.txt"));
Scanner stopwords = new Scanner(new File("undantagsord.txt"));
s.useDelimiter("(\\s|,|\\.|:|;|!|-|\\?|'|\\\")+"); // se handledning
TextProcessor gen = new GeneralWordCounter(stopwords);
while (s.hasNext()) {
String word = s.next().toLowerCase();
gen.process(word);
}
s.close();
gen.report();
}
}
package textproc;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class GeneralWordCounter implements TextProcessor {
private Map<String, Integer> m;
private Scanner excep;
GeneralWordCounter(Scanner r){
Map<String, Integer> m = new HashMap<String, Integer>();
this.m = m;
excep = r;
}
#Override
public void process(String word) {
// TODO Auto-generated method stub
boolean bin = false;
while(excep.hasNext() && bin == false) {
if(word.equals(excep.next().toLowerCase())) {
bin = true;
}
}
if(!bin) {
if(m.containsKey(word)) {
m.put(word, (m.get(word) + 1));
}
else {
m.put(word, 1);
}
}
}
#Override
public void report() {
// TODO Auto-generated method stub
for(String key : m.keySet()) {
if(m.get(key) >= 200) {
System.out.println(key + " - " + m.get(key));
}
}
}
}
You are using same Scanner instance for stopwords inside the loop, which might be getting exhausted within few number of below loops.
TextProcessor gen = new GeneralWordCounter(stopwords);
while (s.hasNext()) {
String word = s.next().toLowerCase();
gen.process(word);
}
Imagine this way, you have started above loop and passed the Scanner instance and when you called process method it started loop for word and reached to end of the file for second Scanner. Now, in the next loop you again called process method but this time pointer will be already at the end of the file as you are using same instance. So, you won't get expected output.
Instead, you need to create new instance of Scanner for each process method call.
public void process(String word) {
Scanner excep = new Scanner(new File("undantagsord.txt"));
// your code.
So I am trying to search through a text file and if the user input is found, it returns the entire sentence including white spaces.But apparently I only get the first string and nothing pass the first string in the sentence. For example if i have a text file called "data.txt" and the contents in the first line is " I am a legend". after user enters "I am a legend" the output after the file is searched is "I". Any help would be appreciated.
public static void Findstr() { // This function searches the text for the string
File file = new File("data.txt");
Scanner kb = new Scanner(System.in);
System.out.println(" enter the content you looking for");
String name = kb.next();
Scanner scanner;
try {
scanner = new Scanner(file).useDelimiter( ",");
while (scanner.hasNext()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(name)) {
// a match!
System.out.println("I found " + name);
break;
}
}
} catch (IOException e) {
System.out.println(" cannot write to file " + file.toString());
}
package com.example;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileSearch {
public void parseFile(String fileName,String searchStr) throws FileNotFoundException{
Scanner scan = new Scanner(new File(fileName));
while(scan.hasNext()){
String line = scan.nextLine().toLowerCase().toString();
if(line.contains(searchStr)){
System.out.println(line);
}
}
}
public static void main(String[] args) throws FileNotFoundException{
FileSearch fileSearch = new FileSearch();
fileSearch.parseFile("src/main/resources/test.txt", "am");
}
}
test.txt contains:
I am a legend
Hello World
I am Ironman
Output:
i am a legend
i am ironman
The above code does case insensitive search. You should use nextLine() to get the complete line. next() breaks on whitespaces.
Reference:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()
Scanner.next(); returns the next caracter instead use Scanner.readLine();
Edit:
Belive Scanners use .nextLine(); not .readLine();
When you are scanning your input..
Scanner kb = new Scanner(System.in);
System.out.println(" enter the content you looking for");
String name = kb.next();
You are accepting only one token. You should accept whole line to be searched as your token using kb.nextLine()
Okay, first post, yay!
Now I know this topic has been beaten to death already. But here's the question :
Write a program that reads words separated by spaces from a text file
and displays words in ascending order. (If two words are the same,
display only one). Pass the text filename from the command line.
Assume that the text file contains only words separated by spaces.
Now I have the reading from the file part figured out. But how do I "pass the filename from the command line"? And then there's the uniqueness factor.
Help?
Edit:
Thanks guys for your help. Here's where I stand now:
import java.io.*;
import java.util.*;
public class Splittext {
public static void main(String[] args) {
String fileName = args[0];
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader(fileName)));
while (s.hasNext()) {
System.out.println(s.next());
}
} catch (FileNotFoundException fnfe) {
System.exit(0);
} finally {
if (s != null) {
s.close();
}
}
TreeSet<String> ts = new TreeSet<String>();
ts.add(s);
Iterator it = ts.iterator();
while(it.hasNext()) {
String value = (String)it.next();
System.out.println("Result :" + result);
}
}
}
But this yields : No suitable method for add (java.util.Scanner); method java.util.TreeSet.add(java.lang.String) is not applicable.
Sorry for the noob questions! Really appreaciate the help :)
Do like this.
public static void main(String args[]) {
String fileName = args[0];
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader(fileName));
while (s.hasNext()) {
System.out.println(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
}
Run this like
java classname readthisfile.txt
Your main function has String[] args passed into to it when you kick off your application, this is where you access you input arguments.
e.g.:
java -cp . my.class.Example Happy Days
Would see the Example class receiving this:
public static void main(String[] args) {
// args.length == 2
// args[0] = "Happy"
// args[1] = "Days"
}
But how do I "pass the filename from the command line"?
public static void main(String args[])
{
final String filename = args[0];
// ...
}
And then there's the uniqueness factor.
And sorting factor.
Insert all the words into TreeSet.
Iterate through it and print values. They will be sorted and unique.