What i can use? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What i can use?

I need to count replaced lines in .txt file using Java, Take my thanks for any information about it

26th Apr 2021, 1:00 AM
Edgars Rukmans
Edgars Rukmans - avatar
2 Answers
+ 1
import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class OverwriteLine {    public static void main(String args[]) throws IOException {       //Instantiating the File class       String filePath = "D://input.txt";       //Instantiating the Scanner class to read the file       Scanner sc = new Scanner(new File(filePath));       //instantiating the StringBuffer class       StringBuffer buffer = new StringBuffer();       //Reading lines of the file and appending them to StringBuffer       while (sc.hasNextLine()) {          buffer.append(sc.nextLine()+System.lineSeparator());       }       String fileContents = buffer.toString();       System.out.println("Contents of the file: "+fileContents);       //closing the Scanner object       sc.close();       String oldLine = "No preconditions and no impediments. Simply Easy Learning!";       String newLine = "Enjoy the free content";       //Replacing the old line with new l
29th Apr 2021, 1:17 AM
Benjamin Salas
Benjamin Salas - avatar
+ 1
  //Replacing the old line with new line       fileContents = fileContents.replaceAll(oldLine, newLine);       //instantiating the FileWriter class       FileWriter writer = new FileWriter(filePath);       System.out.println("");       System.out.println("new data: "+fileContents);       writer.append(fileContents);       writer.flush();    } }
29th Apr 2021, 1:19 AM
Benjamin Salas
Benjamin Salas - avatar