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

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();
}
}
}

Related

Read and edit the file from Java

I'm trying to introduce a line break at every 100th character of the line from the existing file.But it doesn't write anything to it. below is the code written in java to read the existing file and write to it with a temporary file.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class ReplaceFileContents {
public static void main(String[] args) {
new ReplaceFileContents().replace();
}
public void replace() {
String oldFileName = "Changed1.ldif";
String tmpFileName = "Changed2.ldif";
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
line.replaceAll("(.{100})", "$1\n");
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
// Once everything is complete, delete old file..
File oldFile = new File(oldFileName);
oldFile.delete();
// And rename tmp file's name to old file name
File newFile = new File(tmpFileName);
newFile.renameTo(oldFile);
}
}
while ((line = br.readLine()) != null) {
line.replaceAll("(.{100})", "$1\n");
}
First off, line.replaceAll does not replace your line variable with the result. Because Strings are immutable, this method returns the new string, so your line should be line = line.replaceAll(....
Second, you're never writing the new String back into the file. Using replaceAll doesn't change the file itself in any way. Instead, try using your bw object to write the new String to the same line.
From what you've published here, you never try to write line back to bw. Try this:
package hello;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
new Test().replace();
}
public void replace() {
String oldFileName = "d:\\1.txt";
String tmpFileName = "d:\\2.txt";
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
line = line.replaceAll("(.{100})", "$1\n");
bw.write(line);
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
// Once everything is complete, delete old file..
File oldFile = new File(oldFileName);
oldFile.delete();
// And rename tmp file's name to old file name
File newFile = new File(tmpFileName);
newFile.renameTo(oldFile);
}
}
You never try to write line back to bw;
String#replaceAll will return the copy of the source not the original String;

multiple words replace in txt file using 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

Java Writing to a file: does not write to all desired files

I am out of ideas, I've been trying for the whole day to separate one file which has a format of :
AN Aixas
AN Aixirivall
AN Aixovall
AN Andorra la Vella
BR Salto do Mandira
BR Salto do Norte
BR Salto Dollman
BR Salto Grande
BR Salto Pilao
...
and so one, into different files by the name of the Country "AA.txt" and to include all the cities in these separate files. But my program only writes to a certain bunch of files and I cannot figure out why.
I've tried all the writing files classes - same result.
Here is the result, all worked but on a certain bunch of files only.
Here is the code :
package com.fileorganizer;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class File2 implements Cloneable {
static InputStream fis = null;
static BufferedReader br = null;
static String state = "";
static String tmp = "";
static File file = null;
static FileWriter fw = null;
static BufferedWriter bw = null;
public static void main(String[] args) {
int a = 0;
try {
fis = new FileInputStream(
new File(
"/Users/Mihail/Documents/WorkSpace/Parse-Starter-Project-1.8.2/ParseStarterProject/res/raw/cities.txt"));
br = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = br.readLine()) != null) {
state = line.substring(0, 2);
if (state.substring(0, 1).matches("^[A-Z]+$")
&& state.substring(1, 2).matches("^[A-Z]+$")
&& !tmp.equals(state)) {
file = new File(
"/Users/Mihail/Documents/WorkSpace/Parse-Starter-Project-1.8.2/ParseStarterProject/res/raw/countriesFolder/"
+ state + ".txt");
fw = new FileWriter(file.getAbsoluteFile());
bw = new BufferedWriter(fw);
tmp = state;
}
bw.write(line.substring(3) + "\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (Exception ex) {
}
}
}
}
I am really sorry for such a dumb question. Please help
You don't close bw anywhere, so the contents in the BufferedWriter's buffer are lost.

Program in Java to read any file and find a substring, and replace it with another string

This is the code I've come through. What I am trying to reach through this is to edit an XML file and code and put special characters like | (pipe) in place of &#x7c and so on.
class FileReplace
{
ArrayList<String> lines = new ArrayList<String>();
String line = null;
public void doIt()
{
try
{
File f1 = new File("C:/file.xml");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while (line = br.readLine() != null)
{
if (line.contains("|"))
line = line.replace("|", "|");
lines.add(line);
}
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.writeline(s);
out.flush();
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally {
fr.close();
br.close();
out.close()
}
}
public static void main(String args[])
{
FileReplace fr = new FileReplace();
fr.doIt();
}
}
I tried and reached following error,
Please help. Thanks
This will Work
FileReplace.java
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.util.ArrayList;
public class FileReplace {
ArrayList<String> lines = new ArrayList<String>();
String line = null;
public void doIt() {
File f1=null;
FileReader fr=null;
BufferedReader br=null;
FileWriter fw=null;
BufferedWriter out=null;
try {
f1 = new File("src/test.xml");
fr = new FileReader(f1);
br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
if (line.contains("|"))
line = line.replace("|", "|");
lines.add(line);
}
fw = new FileWriter(f1);
out = new BufferedWriter(fw);
for (String s : lines)
out.write(s);
out.flush();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try{
fr.close();
br.close();
out.close();
}catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
public static void main(String args[]) {
FileReplace fr = new FileReplace();
fr.doIt();
}
}
test.xml before running program
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove|</to>
<from>Jani</from>
<heading>Reminder|</heading>
<body>Don't forget me this weekend!</body>
</note>
test.xml after running program
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove|</to>
<from>Jani</from>
<heading>Reminder|</heading>
<body>Don't forget me this weekend!</body>
</note>
Let me know if u face any issues .....
Change Close() to close() and close your readers / writers in a finally block and it will work.
You can also use a try-with-resources statement.
Your class is missing the closing brace }, so the class file can't be parsed.
Also, in your doIt(), don't call close() on any of the readers or writers in the try-block. The finally will handle this nicely for you. :)
Right now, you're closing it in the try, then when everything has completed without errors, trying to close an already closed reader or writer again in the finally block.

How do make output have more than one string (Java)

I asked a similar question before regarding I/O using Java.
I'm trying to copy a list of strings into another file.
package file;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class File {
public static void main(String[] args) {
FileWrite fW = new FileWrite();
try (BufferedReader br = new BufferedReader(new FileReader("B:\\inLarge.dat")))
{
String stCurrent;
while ((stCurrent = br.readLine()) != null) {
System.out.println(stCurrent);
fW.serializeAddress(stCurrent, stCurrent);
}
} catch (IOException e) {
e.printStackTrace();
}
//fW.serializeAddress("Boston", "Canada");
}
}
And
package file;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.io.File;
import java.io.IOException;
public class FileWrite {
public void serializeAddress(String city, String country){
try
{
File file = new File("B:\\outLarge.txt");
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(city + " " + country);
bw.close();
System.out.println("Done");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
But the ending output file has only one result, how do I make it copy everything?
I am thinking buffered-writer somehow needs to be in the loop to write new ones on top of existing ones? But not sure how to implement that.
Thanks a lot.
You are overwriting the file contents every time you call your serialize method, because you didn't open the file in append mode. To prevent overwriting, open the file in append mode:
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
However, this is one case where the solution is probably over-engineered. For efficiency you really should be opening your file just once. Here's an example:
public static void main(final String[] args) {
try {
final BufferedReader reader = new BufferedReader(new FileReader("infile.txt"));
final PrintWriter writer = new PrintWriter(new File("outfile.txt"));
String inputLine;
while((inputLine = reader.readLine()) != null) {
writer.println(inputLine);
}
reader.close();
writer.close();
} catch(final Exception e) {
e.printStackTrace();
}
}
You're overwriting the existing file every time you open it. Instead append to it.
Change
FileWriter fw = new FileWriter(file.getAbsoluteFile());
to
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);

Categories

Resources