multiple words replace in txt file using java - java

I need to replace multiple words in txt file using java. This program only replacing the only one word, in whole file.
import java.io.*;
public class MultiReplace
{
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();
String newtext = oldtext.replaceAll("india", "freedom");
FileWriter writer = new FileWriter("file.txt");
writer.write(newtext);writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}

Try this:
import java.io.*;
public class MultiReplace
{
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)
{
// Replace in the line and append
line = line.replaceAll("india", "freedom");
oldtext += line + "\r\n";
}
reader.close();
FileWriter writer = new FileWriter("file.txt");
writer.write(newtext);
writer.flush();
writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
Refer this to understand why your version is not working.

Your solution is correct!! I ran your program as is and it is able to replace all the india with freedom in the text file

Related

How to delete or remove a specific line from a text file

I was trying to delete a line from a file. I've search on the internet. And i made a method. Here is it.
public void removeLine(BufferedReader br , File f, String Line) throws IOException{
File temp = new File("temp.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
String removeID = Line;
String currentLine;
while((currentLine = br.readLine()) != null){
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(removeID)){
currentLine = "";
}
bw.write(currentLine + System.getProperty("line.separator"));
}
temp.renameTo(f);
bw.close();
br.close();
}
I don't know what is wrong with this method. Could you help me?
Here is where i use this method
delete.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt) {
BufferedReader br = null;
try{
String enterID2 = enterID1.getText().trim();
File books = new File("books.txt");
br = new BufferedReader(new FileReader(books));
removeLine(br , books, enterID2);
System.out.println("done");
}catch (NumberFormatException e1) {
System.out.println("This is not a number");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Delete is a JButton. No error recieved.
Try this code:
public static void removeLine(BufferedReader br , File f, String Line) throws IOException{
File temp = new File("temp.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
String removeID = Line;
String currentLine;
while((currentLine = br.readLine()) != null){
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(removeID)){
currentLine = "";
}
bw.write(currentLine + System.getProperty("line.separator"));
}
bw.close();
br.close();
boolean delete = f.delete();
boolean b = temp.renameTo(f);
}

Program outputs code from multiple methods instead of just one method

I have a Java program that troubleshoots common problems with phones. To do this I have set up a scanner that reads the user input for any keywords. If one of these keywords is found, a method will output from a text file a solution to the problem suggested by that keyword.
My problem is that when I run the program, all the lines from the text file are outputted, from every method, disregarding my input.
Here's the code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class task2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("What is your problem?");
String input = scan.nextLine();
String[] problems = {"screen", "display", "broken", "cracked", "camera", "flash", "ports"};
String[] solutions = input.split("broken");
for(int x=0; x < problems.length; x++){
if(input.contains("broken")){
if(input.contains("screen")){
brokenScreen();
} else{
}
if(input.contains("display")) {
brokenDisplay();
} else{
}
if(input.contains("camera")) {
brokenCamera();
} else{
}
if(input.contains("flash")) {
brokenFlash();
} else{
}
if(input.contains("ports")) {
brokenPorts();
} else{
}
}
else{
}
if(input.contains("cracked")) {
if(input.contains("screen")) {
crackedScreen();
} else{
}
}
if(input.contains("water")) {
waterPhone();
}
else{
}
}
brokenScreen();
brokenDisplay();
crackedScreen();
brokenCamera();
brokenFlash();
brokenPorts();
waterPhone();
noSolution();
}
public static void noSolution() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; //Location of the text file
try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void waterPhone() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenPorts() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenFlash() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenCamera() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void crackedScreen() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenDisplay() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void brokenScreen() {
String file = "C:/Users/Nicholas Gawley/workspace/Second Practice Controlled Assessment/src/solutions.txt"; try {
FileReader filereader = new FileReader(file);
BufferedReader bufferedreader = new BufferedReader(filereader);
while((file = bufferedreader.readLine()) != null){
System.out.println(file);
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can anyone please solve this issue? Any help would be greatly appreciated.
Remove
brokenScreen();
brokenDisplay();
crackedScreen();
brokenCamera();
brokenFlash();
brokenPorts();
waterPhone();
noSolution();
at the end of your main method (after the for loop).

Taking data from multiple files and moving to one file

I some code that takes a file called wonder1.txt and writes the date in that file to another file. Lets say I have more files like wonder2.txt, wonder3.txt, wonder4.txt. How do I write the rest in the same file.
import java.io.*;
import java.util.*;
import java.lang.*;
public class alice {
public static void main(String[] args) throws FileNotFoundException, IOException {
String fileName = ("/Users/DAndre/Desktop/Alice/wonder1.txt");
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = br.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
line = br.readLine();
}
/**
* Pass original file content as string to another method which
* creates new file with same content.
*/
newFile(stringBuilder.toString());
} finally {
br.close();
}
}
public static void newFile(String fileContent) {
try {
String newFileLocation = "/Users/DAndre/Desktop/Alice/new1.txt";
PrintWriter writer = new PrintWriter(newFileLocation);
writer.write(fileContent);//Writes original file content into new file
writer.close();
System.out.println("File Created");
} catch (Exception e) {
e.printStackTrace();
}
}
}
If you have list of files, then you can loop over them one by one. Your current code moves inside the loop.
The easier way would be to put all the files in one folder and read from it.
Something like this :
File folder = new File("/Users/DAndre/Desktop/Alice");
for (final File fileEntry : folder.listFiles()) {
String fileName = fileEntry.getAbsolutePath();
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = br.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
line = br.readLine();
}
/**
* Pass original file content as string to another method which
* creates new file with same content.
*/
newFile(stringBuilder.toString());
} finally {
br.close();
}
}

Code deletes the content of the file rather than replacing a text

In my below code I wanted to replace the text "DEMO" with "Demographics" but instead of replacing the text it deletes the entire content of the text file.
Contents inside the file:
DEMO
data
morning
PS: I'm a beginner in java
package com.replace.main;
import java.io.*;
public class FileEdit {
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
String readLine, replacedData;
try {
bw = new BufferedWriter(
new FileWriter(
"Demg.ctl"));
br = new BufferedReader(
new FileReader(
"Demg.ctl"));
System.out.println(br.readLine()); //I Get Null Printed Here
while ((readLine = br.readLine())!= null) {
System.out.println("Inside While Loop");
System.out.println(readLine);
if (readLine.equals("DEMO")) {
System.out.println("Inside if loop");
replacedData = readLine.replaceAll("DEMO","Demographics");
}
}
System.out.println("After While");
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You open a Writer to your file, but you don't write anything. This means that your file is replaced with an empty file.
Besides this you also need to close your writer, not just the reader.
And last but not least, your if condition is wrong.
if (readLine.equals("DEMO")) {
should read
if (readLine.contains("DEMO")) {
Otherwise it would only return true if your line contained "DEMO" but nothing else.
I'm updating the answer to my own question.
package com.replace.main;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileEdit
{
public static void main(String args[])
{
try
{
BufferedReader reader = new BufferedReader(new FileReader("Demg.ctl"));
String readLine = "";
String oldtext = "";
while((readLine = reader.readLine()) != null)
{
oldtext += readLine + "\r\n";
}
reader.close();
// To replace the text
String newtext = oldtext.replaceAll("DEMO", "Demographics");
FileWriter writer = new FileWriter("Demg.ctl");
writer.write(newtext);
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

File read, changed but how to write out?

Ok, forgive my beginner-ness and please tell me how I can output my text from "before.txt" into a fresh new file called "after". Obviously I have altered the text along the way to make it lower-case and eliminate non alphabetic characters.
import java.io.*;
public class TextReader {
public void openFile() throws IOException {
try {
// Read in the file
BufferedReader br = new BufferedReader(
new FileReader(
new File("before.txt")));
String currentLine = br.readLine();
currentLine = currentLine.toLowerCase();
currentLine = currentLine.replaceAll("[A-Z]", "");
br.close(); // Close br to prevent resource leak
}
// Exception if the file is not in the path specified
catch (Exception e) {
System.out.println("Error: File not found");
}
}
public void writeFile() throws IOException {
BufferedWriter output = new BufferedWriter(new FileWriter("/WS3Ex3/after.txt"));
output.write("before.txt");
output.close();
}
}
What about this
public void openFile() throws IOException {
try {
// Read in the file
BufferedReader br = new BufferedReader(
new FileReader(
new File("before.txt")));
String currentLine = br.readLine();
currentLine = currentLine.toLowerCase();
currentLine = currentLine.replaceAll("[A-Z]", "");
br.close(); // Close br to prevent resource leak
writeFile(currentLine);
}
// Exception if the file is not in the path specified
catch (Exception e) {
System.out.println("Error: File not found");
}
}
public void writeFile(String text) throws IOException {
BufferedWriter output = new BufferedWriter(new FileWriter("/WS3Ex3/after.txt"));
output.write(text);
output.close();
}
}
Let me guess, is this a school assignment?
Try this:
public void ReadAndWrite() throws IOException {
try {
// Read in the file
BufferedWriter output = new BufferedWriter(new FileWriter("/WS3Ex3/after.txt"));
BufferedReader br = new BufferedReader(
new FileReader(
new File("before.txt")));
String currentLine;
while((currentLine = br.readLine()) != NULL){
currentLine = currentLine.toLowerCase();
currentLine = currentLine.replaceAll("[A-Z]", "");
output.write(currentLine);
}
br.close(); // Close br to prevent resource leak
output.close();
}
// Exception if the file is not in the path specified
catch (Exception e) {
System.out.println("Error: File not found");
}
}

Categories

Resources