8

Let's say I have the following code:

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 EditFile {

    public static void main(String[] args) {

        try{
            String verify, putData;
            File file = new File("file.txt");
            file.createNewFile();
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("Some text here for a reason");
            bw.flush();
            bw.close();
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            while( br.readLine() != null ){
                verify = br.readLine();
                if(verify != null){
                    putData = verify.replaceAll("here", "there");
                    bw.write(putData);
                }
            }
            br.close();


        }catch(IOException e){
        e.printStackTrace();
        }
    }

}

All I wanted to do was to write something in a text file, in my case "Some text here for a reason". Then to read data from my file, and finally to change my text from my file from "Some text here for a reason" in "Some text there for a reason". I ran the code but all it happens is to write in my file "Some text here for a reason".

I tried to figure out what could be wrong in my code, but unfortunately it was in vain. Any advice or rewrite is highly appreciated from me.

CRUSADER
  • 5,486
  • 3
  • 28
  • 64
Vlad Dumitrache
  • 109
  • 1
  • 1
  • 7
  • The Problem is that you couldn't read from the file ? – Yehia Awad Dec 24 '13 at 01:26
  • 1
    What you're trying to do doesn't make sense - you're trying to `bw.write` after you already `bw.close();`. Further, in general - why would you want to do anything like that ? if you already know what you want to change - write once to file! (instead of writing, reading and re-writing) – Nir Alfasi Dec 24 '13 at 01:28
  • It's corect, I modified and it worked somehow. Check my last comment from the bottom of the page please :). Thanks anyhow. – Vlad Dumitrache Dec 24 '13 at 13:59
  • Isn't something special what I want to write in my file. The main idea is that what I'm trying to do is for practice, and one of my ideas was that: Write something in a text file, then edit the file(changing a string with another) and finally in my existing file to appear only just the changed string. Can you handle it? – Vlad Dumitrache Dec 24 '13 at 16:23

5 Answers5

8

Change your code to that:

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 EditFile {

    public static void main(String[] args) {

        try{
            String verify, putData;
            File file = new File("file.txt");
            file.createNewFile();
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("Some text here for a reason");
            bw.flush();
            bw.close();
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);

            while( (verify=br.readLine()) != null ){ //***editted
                       //**deleted**verify = br.readLine();**
                if(verify != null){ //***edited
                    putData = verify.replaceAll("here", "there");
                    bw.write(putData);
                }
            }
            br.close();


        }catch(IOException e){
        e.printStackTrace();
        }
    }

}

The Problem is that you are calling br.readLine() twice which is provoking the application to read line1 and then line2 and in your case you have just one line which means that your program read it in the conditional form and when it comes to declaring it to the variable verify, it is stopping because you don't have anymore data to read your file.

Yehia Awad
  • 2,898
  • 1
  • 20
  • 31
  • 1
    There are some hazy details: One is that bw.close() must be put before br.close(). So doing this in my file I obtain: "Some text here for a reasonSome text there for a reason". But, what I want to do is to replace "here" with "there". So, I just want to delete from file "Some text here for a reason" and to have only "Some text there for a reason". Thanks. – Vlad Dumitrache Dec 24 '13 at 13:54
1

I would do it this way:

import java.io.*;

public class EditFile {

public static void main(String[] args) {

    try{
        String verify, putData;
        File file = new File("file.txt");
        file.createNewFile();
        FileWriter fw = new FileWriter(file);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write("Some text here for a reason");
        bw.flush();

        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);

        while( (verify=br.readLine()) != null )
        { 
            if(verify != null)
            {
                putData = verify.replaceAll("here", "there");
                bw.write(putData);
            }
        }
        br.close();
        bw.close();

    }catch(IOException e){
    e.printStackTrace();
    }
}
}
Michele La Ferla
  • 6,775
  • 11
  • 53
  • 79
Bhanupriya
  • 11
  • 1
0

use this code, I used it to remove logs and System.out statements in java file. just change the matching and replacing string.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class FileReplace {
    List<String> lines = new ArrayList<String>();
    String line = null;
    Scanner scan = null;

    public void doIt() {
        scan = new Scanner(System.in);

        while (true) {
            try {

                System.out
                        .println("enter qualified file name ex.D:\\shiv\\shiv android all\\Main work space\\Welcomescreen1.java");
                String path = scan.nextLine();
                File f1 = new File(path);
                FileReader fr = new FileReader(f1);
                BufferedReader br = new BufferedReader(fr);
                int i = 0;
                while ((line = br.readLine()) != null) {
                    if (line.contains("System.out")) {
                        line = line.replace("System.out", "//");
                    } else if (line.contains("Log.")) {
                        line = line.replace("Log", "//");
                    }

                    lines.add(i, line);
                    i++;
                }
                fr.close();
                br.close();

                FileWriter fw = new FileWriter(f1);
                BufferedWriter out = new BufferedWriter(fw);
                for (int j = 0; j < lines.size(); j++) {
                    System.out.println(j + "." + lines.get(j));
                    out.append(lines.get(j));
                    out.newLine();
                }

                out.flush();
                out.close();

                System.out
                        .println("====================work done===================");

            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }

    }

    public static void main(String args[]) {

        FileReplace fr = new FileReplace();

        fr.doIt();

    }
}
shiv
  • 625
  • 1
  • 6
  • 12
0
import java.io.*;

public class TextFile
{
    public static void main(String[] args)
    {
        try
        {
            String verify, putData;
            File file = new File("G:\\Dairy.txt");
            file.createNewFile();
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("I am Shah Khalid");
            bw.flush();

            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);

            while( (verify=br.readLine()) != null )
            { 
                if(verify != null)
                {
                    putData = verify.replaceAll("here", "there");
                    //bw.write(putData); 
                }
            }
            br.close();
            bw.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        System.out.println("Shah");
    }
}

There is no need to type bw.write(putData);, because it will just print the statement twice.
Whatever you want in a file, just give the correct path of the file and use the above code accordingly.

ItamarG3
  • 4,092
  • 6
  • 31
  • 44
Shah Khalid
  • 31
  • 1
  • 10
-1
        File file = new File("/tmp/my.txt");
        FileWriter fw;
        BufferedReader br;
        BufferedWriter bw;
        boolean no=false;
        String line;
        String data="";
        String lessonPath="my new line";

    try {
    if(!file.exists()){
        fw = new FileWriter(file);
        bw = new BufferedWriter(fw);
        bw.write(lessonPath);
        bw.flush();
        bw.close();

    }else{

        br = new BufferedReader(new FileReader(file));


        while((line =br.readLine()) !=null){
           if(!no){
           data=line;
           no=true;
           }else{
               data = data+"\n"+line;
           }   
       }
        bw = new BufferedWriter(new FileWriter(file));
        bw.write(data+"\n"+lessonPath);
        bw.flush();
        bw.close();

    }     

    } catch (Exception ex) {
        ex.printStackTrace();
    }
  • Welcome to Stack Overflow! While this answer is probably correct and useful, it is preferred if you [include some explanation along with it](http://meta.stackexchange.com/q/114762/159034) to explain how it helps to solve the problem. This becomes especially useful in the future, if there is a change (possibly unrelated) that causes it to stop working and users need to understand how it once worked. Thanks! – Hatchet Mar 30 '16 at 14:03