Searching for a sentence in a file java [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am really stuck up with this.
I am having an input file say input.txt.
content of input.txt is
Using a musical analogy, hardware is like a musical instrument and software is like the notes played on that instrument.
Now I want to search the text
like a musical instrument
How can I search the above content in input.txt in java. Any help???

Inorder to search a pattern in java, java provides contains() method in String. Try to use that, Following is the snippet of the code that serve the purpose,
public static void main(String[] args) throws IOException {
FileReader reader = new FileReader(new File("sat.txt"));
BufferedReader br = new BufferedReader(reader);
String s = null;
while((s = br.readLine()) != null) {
if(s.contains("like a musical instrument")) {
System.out.println("String found");
return;
}
}
System.out.println("String not found");
}

You can always use the String#contains() method to search for substrings. Here, we will read each line in the file one by one, and check for a string match. If a match is found, we will stop reading the file and print Match is found!
package com.adi.search.string;
import java.io.*;
import java.util.*;
public class SearchString {
public static void main(String[] args) {
String inputFileName = "input.txt";
String matchString = "like a musical instrument";
boolean matchFound = false;
try(Scanner scanner = new Scanner(new FileInputStream(inputFileName))) {
while(scanner.hasNextLine()) {
if(scanner.nextLine().contains(matchString)) {
matchFound = true;
break;
}
}
} catch(IOException exception) {
exception.printStackTrace();
}
if(matchFound)
System.out.println("Match is found!");
else
System.out.println("Match not found!");
}
}

Related

Read lines from a file and compare their equality [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I need to write a progam to read a text file and compare its lines. I want to store them in an array, but I do not how to do this and how to compare, if they are equal.
package pantoum;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Pantoum {
public static void main(String[] args) throws FileNotFoundException {
//get filename input from user
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the full file name: ");
String fileName = keyboard.nextLine();
File inputFile = new File(fileName);
if (inputFile.exists()){
//create scanner to read file
Scanner input = new Scanner(inputFile);
//while (input.hasNext());{
String title = input.next();
System.out.println(title);
}
else
{
System.out.println("Sorry, that file does not exist.");
}
}
}
i personally prefer to use buffered reader when it comes to reading from a text file.
boolean equal=false;
String lines[] =new [10];
// or however long the array needs to be.
int count=0;
BufferedReader infile = new BufferedReader(new FileReader("<Name of file>"));
do {
lines[count] = infile.readLine();
count++;
} while (lines[count] != null);
for(int i=0;i<lines.length();i++) {
for(int j = i+1; j<lines.length()-1;j++){
if(lines[i].equals(lines[j])){
equal=true;
system.out.print(lines[i]+" and "+lines[j]+" are equal");
}}}
if(!equal){
system.out.print("Sorry your text did not equal any text from the text file");
}
i hope this helped and i hope i have explained everything well enough for you to understand, if not feel free to ask.
I personally would read each line into a String[] position and then in a loop check if String[i].equals(String[j]). If you need a rough idea how to code this let me know.
You can just use scanner's nextLine() method to get an entire line and then compare them using String.equals()
something like
String line1 = input.nextLine();
String line2 = input.nextLine();
if(line1.equals(line2){
doStuff();
}

How to print words that only have more than 10 characters from file? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I've got this question and I'm not very sure how to answer it - I am able to read the file but unsure on how to display only the words with more than 10 characters
Although other answers are correct , I recommend using scanner class to read files, as it safely allows to detect end of file conditions and has simpler/more useful utility methods:-
Scanner input = new Scanner(new File("file.txt"));
while(input.hasNextLine())
{
String word = input.nextLine();
if(word.length()>10){
System.out.println(word)
}
}
This should work:
private static void readFile(File fin) throws IOException {
FileInputStream fis = new FileInputStream(fin);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = br.readLine()) != null) {
if(line.length()>10) System.out.println(line);
}
br.close();
}
Suposing you have the word in a String variable called word:
if (word.length() > 10)
System.out.println(word);
PS: google before asking!!
Here's some pseudo code to help you get started
create empty list //where we'll add all the >10char words
read file(split per newline) //see the apache commons api
for each line
split on space
for each word in splitted sentence
if wordLength > 10 add to empty list
print each entry in your filled list
Here is your logic.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws Exception{
FileInputStream fis = new FileInputStream(new File("your.txt")); // path for the text file
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = br.readLine()) != null) {
String st[] = line.split(" ");
for(int i=0; i<st.length; i++){
if(st[i].length()>10) System.out.println(st[i]);
}
}
}
}

Reading string data from file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I want to read string data from file and has to pass each strings in the file for some operation.For ex if my file possess links of a website then I have to extract each link and parse its data.I have already done parsing for sites by passing URL as input.But now I think its favorable to store entire links as string and pass it as argument.So how can I read URL from a file and parse each URL data?Can any one specify the code for doing this?
Assuming your file contains a url on each line do this:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while((line = br.readLine()) != null) {
// do something with line.
}
But you should be more specific in your question. Where is the problem?
This was your code that I read from your comment:
File file = new File("myfil");
try (FileInputStream fis = new FileInputStream(file)) {
int content; while ((content = fis.read()) != -1) { // convert to char and display it
System.out.print((char) content); }
This is that mess fixed up:
File file = new File("myfil");
String fileContent = ""; // String to keep track of file content
try {
FileInputStream fis = new FileInputStream(file);
int content;
while ((content = fis.read()) != -1)
{
fileContent += (char)content; // append this to the file content as char
}
} catch (IOException e) {
System.out.print("Problem reading file");
}
System.out.print(fileContent); // print it
Keep in mind, you will have to import some stuff into your project. These are the import lines, if you don't already have them:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
If you don't wan't to write code at all, just use the FileUtils-class.
import org.apache.commons.io.FileUtils;
...
public void yourMethod() {
List<String> lines = FileUtils.readLines(yourFile);
}
You can use regular expression for get list with all url's of your file and later iterate list for do something.
This is a sample example.
public class GetURL {
public static void extractUrls(String input, List<URL> allUrls)
throws MalformedURLException {
Pattern pattern = Pattern
.compile("\\b(((ht|f)tp(s?)\\:\\/\\/|~\\/|\\/)|www.)"
+ "(\\w+:\\w+#)?(([-\\w]+\\.)+(com|org|net|gov"
+ "|mil|biz|info|mobi|name|aero|jobs|museum"
+ "|travel|[a-z]{2}))(:[\\d]{1,5})?"
+ "(((\\/([-\\w~!$+|.,=]|%[a-f\\d]{2})+)+|\\/)+|\\?|#)?"
+ "((\\?([-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?"
+ "([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)"
+ "(&(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?"
+ "([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)*)*"
+ "(#([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)?\\b");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
allUrls.add(new URL(matcher.group()));
}
}
public static void main(String[] args) throws IOException {
List<URL> allUrls = new ArrayList<URL>();
BufferedReader br = new BufferedReader(new FileReader("./urls.txt"));
String line;
while ((line = br.readLine()) != null) {
extractUrls(line, allUrls);
}
Iterator<URL> it = allUrls.iterator();
while (it.hasNext()) {
//Do something
System.out.println(it.next().toString());
}
}
}
Take a look at Apache Commons FileUtils and method readFileToString(File source) for convert directly file to String.

Simultaneous searching of multiple words in an external file(Java)

The program that I am trying to create is a program that takes words from a user defined file, saves those words as variables and then searches a different user defined file for those words, outputting there location.
The program works up to and including the point where the program takes the words and saves them as variables. The problem with the program is that the search method returns a null result. My main suspicions are that the code in the search method is incompatible with the code in the read method, or that the 2 methods aren't running simultaneously.
The search method is in the searching class and the read method is in the reading class.
Here is my code (Containing all 3 of my classes), please excuse all of the imports.
This is the first class:
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Combination{
public static void main(String[] args) throws FileNotFoundException{
Scanner userInput = new Scanner(System.in);
Reading ReadingObject = new Reading();
System.out.println("Please enter the file that you wish to open");
String temp = userInput.nextLine();
ReadingObject.setFileName(temp);
ReadingObject.read();
Scanner searchForWord = new Scanner(System.in);
Searching SearchingObject = new Searching();
System.out.println("Please enter the file that you would like to search for these words in");
String temp1 = searchForWord.nextLine();
SearchingObject.setFileName(temp1);
SearchingObject.search();
}
}
This is the second class:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
class Reading {
private String file;
public void setFileName(String fileName){
file = fileName;
}
public String getFileName(){
return file;
}
public void read(){
try{
//Choosing the file to open
FileInputStream fstream = new FileInputStream(getFileName());
//Get the object of datainputstream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null;
//Read the file line by line
while((strLine = br.readLine()) != null){
// \\s+ means any number of whitespaces between tokens
String [] tokens = strLine.split("\\s+");
String [] words = tokens;
for(String word : words){
System.out.print(word);
System.out.print(" ");
Searching SearchingObject = new Searching();
SearchingObject.setWord(word);
}
System.out.print("\n");
}
in.close();
}
catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
This is the third class:
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Searching {
private String file1;
public void setFileName(String fileName){
file1 = fileName;
}
public String getFileName(){
return file1;
}
private String word1;
public void setWord(String wordName){
word1 = wordName;
}
public String getWord(){
return word1;
}
public void search() throws FileNotFoundException{
try{
//Choosing the file to open
FileInputStream fstream = new FileInputStream(getFileName());
//Get the object of datainputstream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null;
while((strLine = br.readLine()) != null){
Pattern p = Pattern.compile(getWord());
Matcher m = p.matcher(strLine);
int start = 0;
while (m.find(start)) {
System.out.printf("Word found: %s at index %d to %d.%n", m.group(), m.start(), m.end());
start = m.end();
}
}
}
catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
Any help will be greatly appreciated.
Regards
Your code is hard to read. Your reading class does not only read; it also searches. You should call it something that reflects its intended use. However, it forgets to tell its searching object where to search, and does not pass the reference to this object to anyone else. In this snippet
for (String word : words) {
System.out.print(word);
System.out.print(" ");
searching searchingObject = new searching();
searchingObject.setWord(word);
}
you are essentially not doing anything. The reference to searchingObject is lost forever.
Your reading class should keep an ArrayList of words to be searched for in the searching, instead of instancing searching objects.
Your searching class should take, as a constructor parameter, one of these ArrayLists -- and convert it into a single regex, which is much more efficient than reading the file once per word to search for. You can search for "a", "b" and "c" using the single regular expression "a|b|c". Works with longer words, too. Escape them first to avoid problems.
Oh, and please, please follow naming guidelines. Call your reading a TokenReader, and your searching a WordListSearcher...

Simple hill climbing algorithm? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm trying to use the Simple hill climbing algorithm to solve the travelling salesman problem. I want to create a Java program to do this. I know it's not the best one to use but I mainly want it to see the results and then compare the results with the following that I will also create:
Stochastic Hill Climber
Random Restart Hill Climber
Simulated Annealing.
Anyway back to the simple hill climbing algorithm I already have this:
import java.util.*;
public class HCSA
{
static private Random rand;
static public void main(String args[])
{
for(int i=0;i<10;++i) System.out.println(UR(3,4));
}
static public double UR(double a,double b)
{
if (rand == null)
{
rand = new Random();
rand.setSeed(System.nanoTime());
}
return((b-a)*rand.nextDouble()+a);
}
}
Is this all I need? Is this code even right..? I have a range of different datasets in text documents that I want the program to read from and then produce results.
Would really appreciate any help on this.
----- EDIT ----
I was being an idiot and opened the Java file straight into Eclipse when i should have opened it in notepad first.. here is the code i have now got.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.Reader;
import java.io.StreamTokenizer;
import java.util.ArrayList;
{
//Print a 2D double array to the console Window
static public void PrintArray(double x[][])
{
for(int i=0;i<x.length;++i)
{
for(int j=0;j<x[i].length;++j)
{
System.out.print(x[i][j]);
System.out.print(" ");
}
System.out.println();
}
}
//reads in a text file and parses all of the numbers in it
//is for reading in a square 2D numeric array from a text file
//This code is not very good and can be improved!
//But it should work!!!
//'sep' is the separator between columns
static public double[][] ReadArrayFile(String filename,String sep)
{
double res[][] = null;
try
{
BufferedReader input = null;
input = new BufferedReader(new FileReader(filename));
String line = null;
int ncol = 0;
int nrow = 0;
while ((line = input.readLine()) != null)
{
++nrow;
String[] columns = line.split(sep);
ncol = Math.max(ncol,columns.length);
}
res = new double[nrow][ncol];
input = new BufferedReader(new FileReader(filename));
int i=0,j=0;
while ((line = input.readLine()) != null)
{
String[] columns = line.split(sep);
for(j=0;j<columns.length;++j)
{
res[i][j] = Double.parseDouble(columns[j]);
}
++i;
}
}
catch(Exception E)
{
System.out.println("+++ReadArrayFile: "+E.getMessage());
}
return(res);
}
//This method reads in a text file and parses all of the numbers in it
//This code is not very good and can be improved!
//But it should work!!!
//It takes in as input a string filename and returns an array list of Integers
static public ArrayList<Integer> ReadIntegerFile(String filename)
{
ArrayList<Integer> res = new ArrayList<Integer>();
Reader r;
try
{
r = new BufferedReader(new FileReader(filename));
StreamTokenizer stok = new StreamTokenizer(r);
stok.parseNumbers();
stok.nextToken();
while (stok.ttype != StreamTokenizer.TT_EOF)
{
if (stok.ttype == StreamTokenizer.TT_NUMBER)
{
res.add((int)(stok.nval));
}
stok.nextToken();
}
}
catch(Exception E)
{
System.out.println("+++ReadIntegerFile: "+E.getMessage());
}
return(res);
}
}
You can compare your results against the code repository for the textbook
"Artificial Intelligence a Modern Approach", here is the aima code repository.
Their hill climbing implementation is HillClimbingSearch.java
I'm not sure what the code you pasted has to do with Traveling Salesman. You have a function UR which generates a random number in the interval [a,b).

Categories