Replacing a line in a new textfile - java

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");

Related

How read data from file that is separated by a blank line in Java

For example I have a file "input.txt" :
This is the
first data
This is the second
data
This is the last data
on the last line
And I want to store this data in a ArrayList in this form:
[This is the first data, This is the second data, This is the last data on the last line]
Note: Every data in file is separated by a blank line. How to skip this blank line?
I try this code but it don't work right:
List<String> list = new ArrayList<>();
File file = new File("input.txt");
StringBuilder stringBuilder = new StringBuilder();
try (Scanner in = new Scanner(file)) {
while (in.hasNext()) {
String line = in.nextLine();
if (!line.trim().isEmpty())
stringBuilder.append(line).append(" ");
else {
list.add(stringBuilder.toString());
stringBuilder = new StringBuilder();
}
}
} catch (FileNotFoundException e) {
System.out.println("Not found file: " + file);
}
Blank lines are not really blank. There are end-of-line character(s) involved the terminate each line. An apparent empty line means you have a pair of end-of-line character(s) abutting.
Search for that pair, and break your inputs when found. For example, using something like String::split.
For example, suppose we have a file with the words this and that.
this
that
Let's visualize this file, showing the LINE FEED (LF) character (Unicode code point 10 decimal) used to terminate each line as <LF>.
this<LF>
<LF>
that<LF>
To the computer, there are no “lines”, so the text appears to Java like this:
this<LF><LF>that<LF>
You can more clearly now notice how pairs of LINE FEED (LF) characters delimit each line. Search for the instances of that pairing to parse your text.
You are actually almost there. What you missed is that the last 2 lines need to be handled differently, as there is NO empty-string line at the bottom of the file.
try (Scanner in = new Scanner(file)) {
while (in.hasNext()) {
String line = in.nextLine();
//System.out.println(line);
if (!line.trim().isEmpty())
stringBuilder.append(line).append(" ");
else { //this is where new line happens -> store the combined string to arrayList
list.add(stringBuilder.toString());
stringBuilder = new StringBuilder();
}
}
//Below is to handle the last line, as after the last line there is NO empty line
if (stringBuilder.length() != 0) {
list.add(stringBuilder.toString());
} //end if
for (int i=0; i< list.size(); i++) {
System.out.println(list.get(i));
} //end for
} catch (FileNotFoundException e) {
System.out.println("Not found file: " + file);
}
Output of above:
This is the first data
This is the second data
This is the last data on the last line
I added an if codition right after the while loop in your code and it worked,
List<String> list = new ArrayList<>();
File file = new File("input.txt");
StringBuilder stringBuilder = new StringBuilder();
try (Scanner in = new Scanner(file)) {
while (in.hasNext()) {
String line = in.nextLine();
if (!line.trim().isEmpty()) {
stringBuilder.append(line).append(" ");
}
else {
list.add(stringBuilder.toString());
stringBuilder = new StringBuilder();
}
}
if (stringBuilder.toString().length() != 0) {
list.add(stringBuilder.toString());
}
} catch (FileNotFoundException e) {
System.out.println("Not found file: " + file);
}
System.out.println(list.toString());
I got the below output
[This is the first data , This is the second data , This is the last data on the last line ]

How to remove a particular string in a text file using java?

My input file has numerous records and for sample, let us say it has (here line numbers are just for your reference)
1. end
2. endline
3. endofstory
I expect my output as:
1.
2. endline
3. endofstory
But when I use this code:
import java.io.*;
public class DeleteTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
File file = new File("D:/mypath/file.txt");
File temp = File.createTempFile("file1", ".txt", file.getParentFile());
String charset = "UTF-8";
String delete = "end";
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
for (String line; (line = reader.readLine()) != null;) {
line = line.replace(delete, "");
writer.println(line);
}
reader.close();
writer.close();
}
catch (Exception e) {
System.out.println("Something went Wrong");
}
}
}
I get my output as:
1.
2. line
3. ofstory
Can you guys help me out with what I expect as output?
First, you'll need to replace the line with the new string List item not an empty string. You can do that using line = line.replace(delete, "List item"); but since you want to replace end only when it is the only string on a line you'll have to use something like this:
line = line.replaceAll("^"+delete+"$", "List item");
Based on your edits it seems that you indeed what to replace the line that contains end with an empty string. You can do that using something like this:
line = line.replaceAll("^"+delete+"$", "");
Here, the first parameter of replaceAll is a regular expression, ^ means the start of the string and $ the end. This will replace end only if it is the only thing on that line.
You can also check if the current line is the line you want to delete and just write an empty line to the file.
Eg:
if(line.equals(delete)){
writer.println();
}else{
writer.println(line);
}
And to do this process for multiple strings you can use something like this:
Set<String> toDelete = new HashSet<>();
toDelete.add("end");
toDelete.add("something");
toDelete.add("another thing");
if(toDelete.contains(line)){
writer.println();
}else{
writer.println(line);
}
Here I'm using a set of strings I want to delete and then check if the current line is one of those strings.

Remove a Specific Line From text file

I trying to remove a specific line from a file. But I have a problem in deleting a particular line from the text file. Let's said, my text file I want to remove Blueberry in the file following:
Old List Text file:
Chocolate
Strawberry
Blueberry
Mango
New List Text file:
Chocolate
Strawberry
Mango
I tried to run my Java program, when I input for delete and it didn't remove the line from the text file.
Output:
Please delete:
d
Blueberry
Remove:Blueberry
When I open my text file, it keep on looping with the word "Blueberry" only.
Text file:
Blueberry
Blueberry
Blueberry
Blueberry
Blueberry
Blueberry
Blueberry
Blueberry
My question is how to delete the specific line from the text file?
Here is my Java code:
String input="Please delete: ";
System.out.println(input);
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader (System.in));
line = reader.readLine();
String inFile="list.txt";
String line = "";
while(!line.equals("x"))
{
switch(line)
{
case "d":
line = reader.readLine();
System.out.println("Remove: " + line);
String lineToRemove="";
FileWriter removeLine=new FileWriter(inFile);
BufferedWriter change=new BufferedWriter(removeLine);
PrintWriter replace=new PrintWriter(change);
while (line != null) {
if (!line.trim().equals(lineToRemove))
{
replace.println(line);
replace.flush();
}
}
replace.close();
change.close();
break;
}
System.out.println(input);
line = reader.readLine();
}
}
catch(Exception e){
System.out.println("Error!");
}
Let's take a quick look at your code...
line = reader.readLine();
//...
while (line != null) {
if (!line.trim().equals(lineToRemove))
{
replace.println(line);
replace.flush();
}
}
Basically, you read the first line of the file and then repeatedly compare it with the lineToRemove, forever. This loop is never going to exit
This is a proof of concept, you will need to modify it to your needs.
Basically, what you need to ensure you're doing, is you're reading each line of the input file until there are no more lines
// All the important information
String inputFileName = "...";
String outputFileName = "...";
String lineToRemove = "...";
// The traps any possible read/write exceptions which might occur
try {
File inputFile = new File(inputFileName);
File outputFile = new File(outputFileName);
// Open the reader/writer, this ensure that's encapsulated
// in a try-with-resource block, automatically closing
// the resources regardless of how the block exists
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
// Read each line from the reader and compare it with
// with the line to remove and write if required
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.equals(lineToRemove)) {
writer.write(line);
writer.newLine();
}
}
}
// This is some magic, because of the compounding try blocks
// this section will only be called if the above try block
// exited without throwing an exception, so we're now safe
// to update the input file
// If you want two files at the end of his process, don't do
// this, this assumes you want to update and replace the
// original file
// Delete the original file, you might consider renaming it
// to some backup file
if (inputFile.delete()) {
// Rename the output file to the input file
if (!outputFile.renameTo(inputFile)) {
throw new IOException("Could not rename " + outputFileName + " to " + inputFileName);
}
} else {
throw new IOException("Could not delete original input file " + inputFileName);
}
} catch (IOException ex) {
// Handle any exceptions
ex.printStackTrace();
}
Have a look at Basic I/O and The try-with-resources Statement for some more details
Reading input from console, reading file and writing to a file needs to be distinguished and done separately. you can not read and write file at the same time. you are not even reading your file. you are just comparing your console input indefinitely in your while loop.In fact, you are not even setting your lineTobeRemoved to the input line. Here is one way of doing it.
Algorithm:
Read the console input (your line to delete) then start reading the file and looking for line to delete by comparing it with your input line. if the lines do not match match then store the read line in a variable otherwise throw this line since you want to delete it.
Once finished reading, start writing the stored lines on the file. Now you will have updated file with one line removed.
public static void main(String args[]) {
String input = "Please delete: ";
System.out.println(input);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
String line = reader.readLine();
reader.close();
String inFile = "list.txt";
System.out.println("Remove: " + line);
String lineToRemove = line;
StringBuffer newContent = new StringBuffer();
BufferedReader br = new BufferedReader(new FileReader(inFile));
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
newContent.append(line);
newContent.append("\n"); // new line
}
}
br.close();
FileWriter removeLine = new FileWriter(inFile);
BufferedWriter change = new BufferedWriter(removeLine);
PrintWriter replace = new PrintWriter(change);
replace.write(newContent.toString());
replace.close();
}
catch (Exception e) {
e.printStackTrace();
}
}

Writing in a new text file

I read a file and create a new file that copies some part of it, removes some lines and replaces them with others. The input arraystring raw is of type [Aaa,Bbb,Ccc,..] and is used to replace part of the line.
In the new file, the non edited parts are printed properly, but the edited parts are printed this way. 1st one is printed, 2nd one not, 3rd yes, 4th no,5th yes... It looks like when I edit a line I erase the one below too. I tried removing out.write("\n") or scanner.nextLine() , but it didnt work either. Any ideas what could i try? Thanks in advance
For example:
OLD TEXT:
.....
LINE 6 / contains j(ac)
LINE 7 / contains i(ac)
LINE 8 / contains k(ac)
LINE 9 / contains mp(ac)
LINE 10 /contains bp(ac)
.....
NEW TEXT (NEW FILE):
.....
LINE NEW6
LINE NEW7
LINE NEW8
LINE NEW9
LINE NEW10
.....
public static void main(String[] args) {
new class();
class.query();
File file = new File("file");
File filenew = new File("file");
try {
PrintWriter out = new PrintWriter(new FileWriter(filenew, true));
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains("j(ac)")) {
String newline = line.replaceAll("/.*?/", "/"+raw1+"/");
scanner.nextLine();
out.write(newline);
out.write("\n");
} else if (line.contains("i(ac)")) {
String newline = line.replaceAll("/.*?/", "/"+raw2+"/");
scanner.nextLine();
out.write(newline);
out.write("\n");
} else if (line.contains("k(ac)")) {
String newline = line.replaceAll("/.*?/", "/"+raw3+"/");
scanner.nextLine();
out.write(newline);
out.write("\n");
}else if (line.contains("mp(k)")) {
String newline = line.replaceAll("/.*?/", "/"+raw4+"/");
scanner.nextLine();
out.write(newline);
out.write("\n");
}else if (line.contains("bp(k)")) {
String newline = line.replaceAll("/.*?/", "/"+raw5+"/");
scanner.nextLine();
out.write(newline);
out.write("\n");
} else{
out.write(line);
out.write("\n");
}
}
out.flush();
out.close();
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is how it suppose to go from the information you provided in your comment.
Its line.contains that shows when i want to edit and which line.
That line that contains"" is the one I want to replace.
And all ifs I include should be used and printed.
String line;
while (scanner.hasNextLine()) {
// Get the line
line = scanner.nextLine();
// if line contains xxx then replace
if (line.contains("j(ac)")) {
line = line.replaceAll("/.*?/", "/"+raw1+"/");
} else if (line.contains("i(ac)")) {
line = line.replaceAll("/.*?/", "/"+raw2+"/");
} else if (line.contains("k(ac)")) {
line = line.replaceAll("/.*?/", "/"+raw3+"/");
}else if (line.contains("mp(k)")) {
line = line.replaceAll("/.*?/", "/"+raw4+"/");
}else if (line.contains("bp(k)")) {
line = line.replaceAll("/.*?/", "/"+raw5+"/");
}
// Write the line with replaced items
out.write(line);
out.write("\n");
}
Now what your code doing:
while (scanner.hasNextLine()) {
// get the line (very first line) and store that in "line"
String line = scanner.nextLine();
// check if line contains "j(ac)"
if (line.contains("j(ac)")) {
// if "line" contains replace everything and save it to "newline"
String newline = line.replaceAll("/.*?/", "/"+raw1+"/");
// get next line getting used for nothing (second line stored nowhere)
scanner.nextLine();
// write the newline to output file.
out.write(newline);
out.write("\n");
}
// some more if else blocks executing same patterns explained above
else{
// if nothing contains in "line" then write to output file
out.write(line);
out.write("\n");
}
}

Searching content of a file

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) {
}

Categories