Remove line from text file if it contains string java - java

I want to do read from text file, if I find certain email then I want to remove the entire line.
So I want to remove email555#email.com
stuffherestuffemail555#email.comstuffstuff
otherrandomwordsinrandomorder
reandom word and spaces maybe # and charcters email555#email.com
APPLEPEARAPPLE
CATDOGCAT
CATDOGPEARemail555#email.comDogPear
To this
otherrandomwordsinrandomorder
APPLEPEARAPPLE
CATDOGCAT
Code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class SendReq {
public static void main(String[] args) throws FileNotFoundException,
IOException{
File inputFile = new File("testfile.txt");
if (!inputFile.exists()){
inputFile.createNewFile();
}
File tempFile = new File("tempfile.txt");
if (!tempFile.exists()){
tempFile.createNewFile();
}
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "NAMEOFEMAIL#EMAIL.com";
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
}
}

Related

java update txt file content line by line

I am trying to update a txt file in place, namely without creating a temp file or writing a file in a new file destination but I've tried all the solutions on stack overflow and none of these have worked so far.
It always give me an empty file as result. it simply delete all the content of the source file.
So I am trying to modify the following code, which takes two files as input, in order to take only one input (the file source) but without success.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
public class CopyFiles {
private static void copyFile(String sourceFileName, String destinationFileName) {
try (BufferedReader br = new BufferedReader(new FileReader(sourceFileName));
PrintWriter pw = new PrintWriter(new FileWriter(destinationFileName))) {
String line;
while ((line = br.readLine()) != null) {
line += " ENDING ";
pw.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String destinationFileName = "destination.csv";
String sourceFileName = "source.csv";
copyFile(sourceFileName, destinationFileName);
}
}

How to delete a line from a text file based on certain criteria

Just wondering if anyone would know how to iterate through a csv file and based on a set of rules, delete various lines. Or, alternatively the lines that satisfy the rules can be added to a new output.csv file.
So far I have managed to read the csv file and add each line to an ArrayList. But now I need to apply a set of rules to these lines (preferably using an if statement) and delete lines that do not fit the criteria.
package codeTest;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws IOException {
String filename = "sample.csv";
try(Stream<String> stream = Files.lines(Paths.get(filename))){
stream.forEach(System.out::println);
try {
File inputFile = new File("sample.csv");
File outputFile = new File("Output.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
String strLine;
java.util.ArrayList<String> list = new java.util.ArrayList<String>();
while((strLine = reader.readLine()) != null){
list.add(strLine);
}
System.out.println("\nTEST OUTPUT..........................\n");
Stream<String> lineToRemove = list.stream().filter(x -> x.contains("yes"));
} catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
}
Any suggestions?
I am in complete coders block if there is such a thing.
You can use Files.write method:
List<String> filtered = Files.lines(Paths.get(filename)).
filter(x -> x.contains("yes")).collect(Collectors.toList());
Files.write(Paths.get("Output.txt"),filtered);

how to remove empty line in a file in java

I am converting a pdf file to text and removing lines which have page number but the problem is that it leaving an empty space of 2 line.So i want to remove these spaces which have 2 or more empty line continuously but not if 1 line is empty.my code is :
// Open the file
FileInputStream fstream = new FileInputStream("C:\\Users\\Vivek\\Desktop\\novels\\Me1.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
String s=null;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
String pattern = "^[0-9]+[\\s]*$";
strLine=strLine.replaceAll(pattern, " ");
writeResult("C:\\Users\\Vivek\\Desktop\\novels\\doci.txt",strLine);
}
//Close the input stream
br.close();
}
public static void writeResult(String writeFileName, String text)
{
File log = new File(writeFileName);
try{
if(log.exists()==false){
System.out.println("We had to make a new file.");
log.createNewFile();
}
PrintWriter out = new PrintWriter(new FileWriter(log, true));
out.append(text );
out.println();
out.close();
}catch(IOException e){
System.out.println("COULD NOT LOG!!");
}
}
plz help me.
You can work with sequent empty line counter in your method like SkrewEverything suggested.
Or make a post-processing with regular expressions like this:
package testingThings;
import java.awt.Desktop;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class EmptyLinesReducer {
public Path reduceEmptyLines(Path in) throws UnsupportedEncodingException, IOException {
Path path = Paths.get("text_with_reduced_empty_lines.txt");
String originalContent = new String(Files.readAllBytes(in), "UTF-8");
String reducedContent = originalContent.replaceAll("(\r\n){2,}", "\n\n");
Files.write(path, reducedContent.getBytes());
return path;
}
public Path createFileWithEmptyLines() throws IOException {
Path path = Paths.get("text_with_multiple_empty_lines.txt");
PrintWriter out = new PrintWriter(new FileWriter(path.toFile()));
out.println("line1");
//empty lines
out.println();
out.println();
out.println();
out.println("line2");
//empty lines
out.println();
out.println("line3");
//empty lines
out.println();
out.println();
out.println();
out.println();
out.println();
out.println("line4");
out.close();
return path;
}
public static void main(String[] args) throws UnsupportedEncodingException, IOException {
EmptyLinesReducer app = new EmptyLinesReducer();
Path in = app.createFileWithEmptyLines();
Path out = app.reduceEmptyLines(in);
// open the default program for this file
Desktop.getDesktop().open(out.toFile());
}
}

removing empty lines from txt file

I manage to get this code working. It reads test.txt with about 10000 words (each word in its own line) and formats them first Alphabeticly and second BY length. However when i open sort.txt i get first like a lot of empty lines after that the words are properly formated. My question is how to remove thos empty lines since they cant be there. Will .trim work?
package test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class sort {
public static class MyComparator implements Comparator<String>{
#Override
public int compare(String o1, String o2) {
if (o1.length() > o2.length()) {
return 1;
} else if (o1.length() < o2.length()) {
return -1;
}
return o1.compareTo(o2);
}
}
public static void main(String[] args) throws Exception {
String inputFile = "test.txt";
String outputFile = "sort.txt";
FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String inputLine;
List<String> lineList = new ArrayList<String>();
while ((inputLine = bufferedReader.readLine()) != null) {
lineList.add(inputLine);
}
fileReader.close();
Collections.sort(lineList,String.CASE_INSENSITIVE_ORDER);
FileWriter fileWriter = new FileWriter(outputFile);
PrintWriter out = new PrintWriter(fileWriter);
for (String outputLine : lineList) {
out.println(outputLine);
}
Collections.sort(lineList, new MyComparator());
FileWriter Fw = new FileWriter(outputFile);
PrintWriter pw = new PrintWriter(fileWriter);
for (String outputLine : lineList) {
out.println(outputLine);
}
out.flush();
out.close();
fileWriter.close();
}
}
just dont add those empty lines:
while ((inputLine = bufferedReader.readLine()) != null) {
if (!inputLine.isEmpty()) {
lineList.add(inputLine);
}
}
All you need is
for (String outputLine : lineList) {
if (!"".equals(outputLine.trim()))
out.println(outputLine);
//...
You can't use .trim() on its own to solve the problem because it just hacks off whitespace at the beginning and end. It'll leave an empty String unchanged. I've used it here to make sure that you also omit lines that aren't empty but do have just whitespace in.
you can handle it when you are actually adding string to list that would be good approach like
while (!StringUtils.isEmpty(inputLine = bufferedReader.readLine())) {
Manage to make it work. Here is the solution. Thanks for all yours replies.
package test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class sort {
public static class MyComparator implements Comparator<String>{
#Override
public int compare(String o1, String o2) {
if (o1.trim().length() > o2.trim().length()) {
return 1;
} else if (o1.trim().length() < o2.trim().length()) {
return -1;
}
return o1.compareTo(o2);
}
}
public static void main(String[] args) throws Exception {
String inputFile = "test.txt";
String outputFile = "sort.txt";
FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String inputLine;
List<String> lineList = new ArrayList<String>();
while ((inputLine = bufferedReader.readLine()) != null) {
lineList.add(inputLine);
}
Collections.sort(lineList,String.CASE_INSENSITIVE_ORDER);
Collections.sort(lineList, new MyComparator());
FileWriter fileWriter = new FileWriter(outputFile);
PrintWriter out = new PrintWriter(fileWriter);
FileWriter Fw = new FileWriter(outputFile);
PrintWriter pw = new PrintWriter(Fw);
for (String outputLine : lineList) {
if (!"".equals(outputLine.trim()))
out.println(outputLine); }
out.flush();
out.close();
fileWriter.close();
}
}

String Tokenizing error occurs

there is a text file which we read from it , then we want to write it after some little changes to othere text file, but the question is that why it has different results if we use
System.out.println and when we use pwPaperAuthor.println?
the code is like :
package cn.com.author;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
//input:"IndexAuthors1997-2010.txt"
//output:"PaperAuthor1997-2010.txt"
public class PaperAuthors {
public static void main(String[] args) {
BufferedReader brIndexAuthors = null;
BufferedWriter bw = null;
PrintWriter pwPaperAuthor = null;
try {
brIndexAuthors = new BufferedReader(new InputStreamReader(
new FileInputStream("IndexAuthors1997-2010.txt")));
bw = new BufferedWriter(new FileWriter(new File(
"PaperAuthor1997-2010.txt")));
pwPaperAuthor = new PrintWriter(new OutputStreamWriter(
new FileOutputStream("PaperAuthor1997-2010.txt")));
/*
* line = brIndexAuthors.readLine();
*
* element=line.split("#"); String author=null; StringTokenizer st =
* new StringTokenizer(element[1],","); while(st.hasMoreTokens()) {
* author = st.nextToken(); pwPaperAuthor.println(element[0] + "+" +
* author); //~i++; }
*/
String line = null;
String element[] = new String[3];
String author = null;
int i = 0;
while ((line = brIndexAuthors.readLine()) != null) {
element = line.split("##");
StringTokenizer st = new StringTokenizer(element[1], ",");
int num=st.countTokens();
while (st.hasMoreTokens()) {
author = st.nextToken();
pwPaperAuthor.println(element[0]+"#"+author+"#"+element[2]);
bw.write(element[0] + "#" + author + "#" + element[2]);
bw.newLine();
System.out.println(element[0]+"#"+author+"#"+element[2]);
i++;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
Ouput
if
System.out.println(element[0]+"#"+author+"#"+element[2]);------>620850#Henk Ern
if
pwPaperAuthor.println(element[0]+"#"+author+"#"+element[2]);
----->620850#Henk Ernstblock#2001
There's no way you can read a file and write to it in the same loop, using the stream-based API. You will have to create a new file and copy everything that's the same, adding what's new. What you are doing now has unpredictable behavior. If you still want to read and write at the same time, you'll have to use the RandomAccessFile, but that's quite a bit more complicated.

Categories