Creating, writing and editing same text file in ja

2019-02-10 04:53发布

问题:

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.

回答1:

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.



回答2:

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


回答3:

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

    }
}


回答4:

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.



回答5:

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