Searching content of a file - java

I dont have alot of experience working with files. I have a file. I have written the following to the file
Test 112
help 456
news 456
Friendly 554
fileOUT.write("Test 112\r\n");//this is a example of how I entered the data.
Now I am trying to search in the file for the word news and display all the content that is in that line that contains the word news.
This is what I have attempted.
if(fileIN.next().contains("news")){
System.out.println("kkk");
}
This does not work. The folowing does find a word news because it displays KKK but I dont have an Idea how to display only the line that it news was found in.
while(fileIN.hasNext()){
if(fileIN.next().contains("Play")){
System.out.println("kkk");
}
}
What must be displayed is news 456.
Thank You

You want to call fileIN.nextLine().contains("news")
Try using the Scanner class if you are not already. It does a wonderful job of splitting input from a stream by some delineator (in this case the new line character.)
Here's a simple code example:
String pathToFile = "data.txt";
String textToSearchFor = "news";
Scanner scanner = new Scanner(pathToFile);
while(scanner.hasNextLine()){
String line = scanner.nextLine();
if(line.contains(textToSearchFor)){
System.out.println(line);
}
}
scanner.close();
And here's an advanced code example that does much more than you asked. Enjoy!
//Search file for an array of strings. Ignores case if caseSensitive is false.
public void searchFile(String file, boolean caseSensitive, String...textToSearchFor){
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()){
String originalLine = scanner.nextLine();
String line = originalLine;
if(!caseSensitive) line = line.toLowerCase();
for(String searchText : textToSearchFor){
if(!caseSensitive) searchText = searchText.toLowerCase();
if(line.contains(searchText)){
System.out.println(originalLine);
break;
}
}
}
scanner.close();
}
//usage
searchFile("data.txt",true,"news","Test","bob");
searchFile("data.txt",true,new String[]{"test","News"});

you can try this code...:D
String s = null;
File file = new File(path);
BufferedReader in;
try {
in = new BufferedReader(new FileReader(file));
while (in.ready()) {
s = in.readLine();
if(s.contains("news")){
//print something
}
}
in.close();
} catch (Exception e) {
}

Related

Reading file from String to String using Scanner

I'm creating a program, where i must read special text files. I have a problem with a reading text from specified word to another specified word(not including these words). Is using a scanner a good approach to this problem?
I mean something like that:
"text1
text2
text3
text4
text5"
And i want to get from it String with "text2 text3 text4".
I tried using useDelimeter but I can not figure out how to apply it to this case. I created a method that allows me to skip lines, but this is not a good solution in the long run and it will work for only one specified file.
Here is one of my methods I want to make it here
private String readFile3(File file) {
try {
Scanner sc = new Scanner(file);
//skipLine(sc, 8);
sc.useDelimiter("R");
String sentence = sc.next();
textAreaD.setText(sentence);
} catch (FileNotFoundException e) {
System.out.println("No file");
}
return null;
}
How about something like this:
private String readFile3(File file) {
try {
Scanner sc = new Scanner(file);
boolean save = false;
String sentence = "";
String temp = "";
while (sc.hasNextLine()) {
temp = sc.nextLine();
if (sentence.contains("text1")) {
if (!save) {
temp = sc.nextLine();
}
save = true;
}
if (sentence.contains("text5")) {
save = false;
}
if (save) {
sentence = sentence + temp;
}
}
// skipLine(sc, 8);
//sc.useDelimiter("R");
sentence = sentence.replaceAll("\\n", "");
textAreaD.setText(sentence);
} catch (FileNotFoundException e) {
System.out.println("No file");
}
return null;
}
Should read out all strings between "text1" and "text5". Maybe you have to do some more formatting and check if "text1" occurs more than one time, if you want to save that too, but i hope it helps you.

replacing a string deletes everything in text

I'm trying to write a program for this question: "Write a program that will ask a string and a file name from the user and then removes all the occurrences of that string from that text file."
This is what I have so far:
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
public class RemoveText {
public static void main(String[] args){
//creates a scanner to read the user's file name
Scanner input = new Scanner(System.in);
System.out.println("Enter a file name: ");
String fileName = input.nextLine();
java.io.File file = new java.io.File(fileName);
java.io.File newFile = new java.io.File(fileName);
Scanner stringToRemove = new Scanner(System.in);
System.out.println("Enter a string you wish to remove: ");
String s1 = stringToRemove.nextLine();
//creating input and output files
try {
Scanner inputFile = new Scanner(file);
//reads data from a file
while(inputFile.hasNext()) {
s1 += inputFile.nextLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//supposed to replace each instance of the user input string
//but instead deletes everything on the file and i don't know why
String s2 = s1.replaceAll(s1, "");
try {
PrintWriter output = new PrintWriter(newFile);
output.write(s2);
output.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//closing various scanners
input.close();
stringToRemove.close();
}
}
But for some reason, instead of replacing the string with whitespace, the entire text file becomes empty. What am I doing wrong?
Edit: Okay, so I took everyone's advice and managed to fix the variable problem by introducing a third String variable and using more descriptive variable names.
Scanner s1 = new Scanner(System.in);
String stringToRemove = s1.nextLine();
String fileContents = null;
try {
//stuff here
while (inputFile.hasNextLine()) {
fileContents += inputFile.nextLine();
} catch { //more stuff }
String outputContent = fileContents.replaceAll(stringToRemove, "");
My issue now is that the beginning of the new file starts with "null" before relaying the new content.
String s2 = s1.replaceAll(s1, "");
the first parameter of replaceAll method is what you are looking for to replace, and you are looking for s1, you are saying with this code clean all s1 content...
Where you went wrong is that you appended the file content to s1 which is the string you want to remove.
Try introduce s3 and then do
s2 = s3.replaceAll(s1, "");

How to remove old data from text file using user input in Java

I am trying to get a user input and see if it matches any sentence in a text file. If so I want to remove the sentence. I mean I have the searching implementation so far all I need is help removing the sentence and possibly rewrite to the text file. I am not familiar with Java. Any help would be appreciated.
public static void searchFile(String s) throws FileNotFoundException {
File file = new File("data.txt");
Scanner keyboard = new Scanner(System.in);
// String lines = keyboard.nextLine();
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile + "is found already");
System.out.println("would you like to rewrite new data?");
String go = keyboard.nextLine();
if (go.equals("yes")) {
// Here i want to remove old data in the file if the user types yes then rewrite new data to the file.
}
}
}
}
I think you can't read and write into file on the same time so, make one temporary file and write all data with replaced text into new file and then move that temp file to original file.
I have appended code bellow, hope this helps.
File f = new File("D:\\test.txt");
File f1 = new File("D:\\test.out");
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String s = "test";
BufferedReader br = new BufferedReader(new FileReader(f));
PrintWriter pr = new PrintWriter(f1);
String line;
while((line = br.readLine()) != null){
if(line.contains(s)){
System.out.println(line + " is found already");
System.out.println("would you like to rewrite new data?");
String go = input.readLine();
if(go.equals("yes")){
System.out.println("Enter new Text :");
String newText = input.readLine();
line = line.replace(s, newText);
}
}
pr.println(line);
}
br.close();
pr.close();
input.close();
Files.move(f1.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);

How to replace particular text in the txt file?

Here is my txt file look like.
admin 12345
funny 123
loop 12390
Hi guys. I am trying to replace particular text in my txt file. For example, I want to replace admin's 12345 with something else that I key in in my input2, it means I want to replace the String(pass) that I find out from txt file through scanner. If I use bufferedwritter, the whole content is going to rewrite..How o solve this problem. I am newbie of programming, kindly need you all help.
login.addActionListener(this);
public void actionPerformed(ActionEvent e) {
String inputUser = input1.getText();
String inputPass = input2.getText();
File loginf = new File("oop.txt");
try{
if(e.getSource()==login)
{
Scanner read = new Scanner(new File("oop.txt"));
boolean loginTry = true;
while(read.hasNext())
{
String user = read.next();
String pass = read.next();
if(inputUser.equals(user) && inputPass.equals(pass)){
loginTry=false;
break;
}
}
if(!loginTry)
{
JOptionPane.showMessageDialog(this,"Login Successful");
}
Here is a simple example on how to do what you want!
//Replace a line or word in a file
import java.io.*;
public class BTest
{
public static void main(String args[])
{
try
{
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
}
reader.close();
// replace a word in a file
//String newtext = oldtext.replaceAll("drink", "Love");
//To replace a line in a file
String newtext = oldtext.replaceAll("This is test string 20000", "blah blah blah");
FileWriter writer = new FileWriter("file.txt");
writer.write(newtext);writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
OUTPUT
file.txt
I drink Java
I sleep Java
This is test string 1
This is test string 20000
I did both because the way your txt file is you have more than just a word, you have an ID number of some sorts right next to your users login information. So i would use change line!

Replacing a line in a new textfile

I have a textfile with several lines.
Line 1
Line 2
Line 3
Line 4
...
I am trying for example to replace line 3 with a new sentence.
I tred using the code below, but instead of replacing it, it just adds the new sentence next to it and the rest of the text as well. I need it to be removed and place the new sentence in the same spot, and then continue the writing of the rest of the lines. What should I fix?
try {
PrintWriter out = new PrintWriter(new FileWriter(filenew, true));
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains(line 2)) {
line = line.replaceAll("", "new sentence");
}
out.write(line);
out.write("\n");
}
out.flush();
out.close();
scanner.close();
}
catch (IOException e) {
e.printStackTrace();
}
Thanks in advance!
The loop you are looking for is something like
String targetText = "... the text to search";
String replacement = "The new text";
PrintWriter out = mkPrintWriter(/*...*/);
while (in.hasNextLine()) {
String line = in.nextLine();
if (line.equals(targetText)) {
out.println(replacement);
} else {
out.println(line);
}
}
Note that the out file is a temporary resource. After processing, you can unlink the old file and rename the temp file.
Change
line = line.replaceAll("", "new sentence");
to
line = line.replaceAll(line 2, "new sentence");

Categories