Searching through a text file java - java

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

Related

Uppercase Conversion

import java.util.Scanner;
import java.io.*;
public class UppercaseFileConverter {
public static void main(String[] args) throws FileNotFoundException{
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of the file to be read: Here is the file converted into Uppercase.");
String fileName = input.nextLine();
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
//validates that the file exists
if (!file.exists()) {
System.out.println("The file " + fileName + " does not exist or could not be opened.");
System.exit(0);
}
//if file exists then reads each line and prints the upper case
else {
while (inputFile.hasNext()) {
String line = inputFile.nextLine();
System.out.println(line.toUpperCase());
}
}
inputFile.close();
System.out.println("Files read, converted and then closed.");
}
}
When I run my code, my validation that checks whether the file entered exists or not does not run but instead terminates the program. Can I use a try/catch?
You can do three things
1.Remove System.exit()
2.Add null Check before using file object
if (file!=null&&!file.exists()) {}
3.Add try catch block to handle possible exception in your case FileNotFoundException.

Aligning string to center of .txt file

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
public class fileprint {
public static void main(String args[]){
String title;
String desc;
//scanner
Scanner sc = new Scanner(System.in);
//--file--//
String fileName = "print.txt";
PrintWriter writer = null;
try
{
writer = new PrintWriter(fileName);
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
//--end--//
System.out.print("Enter a title:");
title = sc.nextLine();
writer.println(title);
do
{
System.out.println("Enter a description: ");
desc = sc.nextLine();
writer.println(desc);
}while(!desc.equals("END"));
writer.close();
}//end main
}//end class
Above is my code, I have successfully completed the program and it's functioning as intended. However I would like the printed string (title) in .txt file to be aligned in the center of my description. My current output in the .txt file is like this:
As you can see, the word "title" is at the most left of the .txt file and I would like it to be in the center of "cats and dogs" and "are best friends." I am also trying to remove the word "END" from the .txt file, this was not intended but writer.print(value) has taken in "END" and has printed it to the .txt file. What are my options here?

Scanner issue! Code is skipping the first user input and printing twice instead of once ONLY on the first iteration

https://courses.cs.washington.edu/courses/cse142/15sp/homework/6/spec.pdf
EDIT* Input Files are here:(sorry i'm new to stack overflow, hopefully this works)
I've also tried console.next() but it gives different errors than console.nextLine() in the rePlaceholder method. **
tarzan.txt - https://pastebin.com/XDxnXYsM
output for tarzan should look like this: https://courses.cs.washington.edu/courses/cse142/17au/homework/madlibs/expected_output_1.txt
simple.txt https://pastebin.com/Djc2R0Vz
clothes.txt https://pastebin.com/SQB8Q7Y8
this code should print to an output file you name.
Hello, I have a question about scanners because I don't understand why the code
is skipping the user input on the first iteration but works fine on the rest.
I'm writing a code to create a madlib program and the link will provide the explanation to the program but pretty much you have these placeholders in a text file and when you see one, you prompt for user input to replace it with your own words. However, my program always go through TWO placeholders first and only ask the user input for one, completely skipping the first placeholder. What is wrong with my code??? Also, how do you fix this? Everything else is running perfectly fine, only that the first line is consuming two placeholders so I'm always off by one.
Welcome to the game of Mad Libs.
I will ask you to provide various words
and phrases to fill in a story.
The result will be written to an output file.
(C)reate mad-lib, (V)iew mad-lib, (Q)uit? c
Input file name: tarzan.txt
Output file name: test.txt
Please type an adjective: Please type a plural noun: DD DDDD <--- why is it like this
Please type a noun: DDDD
Please type an adjective: DD
Please type a place:
========================================================================
package MadLibs;
import java.util.*;
import java.io.*;
public class MadLibs2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
intro();
boolean isTrue = true;
while(isTrue) {
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
String choice = console.next();
if (choice.equalsIgnoreCase("c")) {
create(console);
}
else if (choice.equalsIgnoreCase("v")) {
view(console);
}
else if (choice.equalsIgnoreCase("q")) {
System.exit(0);
}
}
}
public static void view(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String viewFile = console.next();
File existingMadLib = new File(viewFile);
Scanner printText = new Scanner(existingMadLib);
while(printText.hasNextLine()) {
System.out.println(printText.nextLine());
}
}
public static void create(Scanner console) throws FileNotFoundException {
System.out.print("Input file name: ");
String inputFile = console.next();
File newMadLib = new File(inputFile);
while(!newMadLib.exists()) {
System.out.print("File not found. Try again: ");
inputFile = console.next();
newMadLib = new File(inputFile);
}
System.out.print("Output file name: ");
String outputFile = console.next();
System.out.println();
PrintStream output = new PrintStream(new File(outputFile));
Scanner input = new Scanner(newMadLib);
while(input.hasNextLine()) {
String line = input.nextLine();
outputLines(line, output, console);
}
}
public static void outputLines(String line, PrintStream output, Scanner console) throws FileNotFoundException{
String s = "";
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext()){
s = lineScan.next();
if(s.startsWith("<") || s.endsWith(">")) {
s = rePlaceholder(console, lineScan, s);
}
output.print(s + " ");
}
output.println();
}
public static String rePlaceholder(Scanner console, Scanner input, String token) {
String placeholder = token;
placeholder = placeholder.replace("<", "").replace(">", "").replace("-", " ");
if (placeholder.startsWith("a") || placeholder.startsWith("e") || placeholder.startsWith("i")
|| placeholder.startsWith("o") || placeholder.startsWith("u")) {
System.out.print("Please type an " + placeholder + ": ");
} else {
System.out.print("Please type a " + placeholder + ": ");
}
String change = console.nextLine();
return change;
}
public static void intro() {
System.out.println("Welcome to the game of Mad Libs.");
System.out.println("I will ask you to provide various words");
System.out.println("and phrases to fill in a story.");
System.out.println("The result will be written to an output file.");
}
}
in your rePlaceholder, change this line:
String change = console.nextLine();
Into this
String change = console.next();
Your problem is that nextLine doesn't wait for your output, just reads what it has in the console, waiting for a new line.
This is from the documentation to be a bit more precise on the explanation:
Since this method continues to search through the input looking for a
line separator, it may buffer all of the input searching for the line
to skip if no line separators are present.
UPDATE
After reading the comment, the previous solution will not work for multiple words.
After reading the output file, you are using next().
You need to make another call to nextLine() to clean the buffer of any newlines.
System.out.print("Output file name: ");
String outputFile = console.next();
console.nextLine(); // dummy call
System.out.println();

How to search a word in file in java

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

Txtfile search not working

Ok so i have inputted a number of records to a text file and i can both write to and read from this file, but i am now attempting to search through this textfile and have encountered a problem.
package assignmentnew;
// Import io so we can use file objects
import java.io.*;
import java.util.Scanner;
public class SearchProp {
public void Search() throws FileNotFoundException {
try {
String details, input, id, line;
int count;
Scanner user = new Scanner(System.in);
System.out.println();
System.out.println();
System.out.println("Please enter your housenumber: ");
input = user.next();
Scanner housenumber = new Scanner(new File("writeto.txt"));
while (housenumber.hasNext())
{
id = housenumber.next();
line = housenumber.nextLine();
if (input.equals(id))
{
System.out.println("House number is: " + id + "and" + line);
break;
}
if(!housenumber.hasNext()) {
System.out.println("no house with this number");
}
}
}
catch(IOException e)
{
System.out.print("File failure");
}
}
}
No matter what value i enter i am told that the house number is not present in the file, but obviously it is, any ideas?
Addendum:
File Structure in textfile.
27,Abbey View,Hexham,NE46 1EQ,4,150000,Terraced
34,Peth Head,Hexham,NE46 1DB,3,146000,Semi Detached
10,Downing Street,London,sw19,9,1000000,Terraced
The default delimiter for a scanner is white-space, and not ,.
You have to use housenumber.useDelimiter(","); and the code will work.
EDIT:
Set it before the while.
And that is what I get for example for 27.
Please enter your housenumber:
27
House number is: 27 and ,Abbey View,Hexham,NE46 1EQ,4,150000,Terraced

Categories

Resources