Creating, writing and editing same text file in java

Creating, writing and editing same text file in java

how to replace a word in a text file using java
how to update data inside a text file in java
reading and editing files in java
how to overwrite a line in a file java
java program to read a text file and write to another file
java write to text file
how to replace a specific line in a file using java
java write to file

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.


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.

Java FileWriter Class, How do you replace one string in a text file in Java? Create a File. To create a file in Java, you can use the createNewFile() method. This method returns a boolean value: true if the file was successfully created, and false if the file already exists. Note that the method is enclosed in a trycatch block.


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

How To Replace Specific String In Text File In Java?, How do you read a file and write to another file in Java? Creating and Writing a File by Using Stream I/O. You can create a file, append to a file, or write to a file by using the newOutputStream(Path, OpenOption) method. This method opens or creates a file for writing bytes and returns an unbuffered output stream. The method takes an optional OpenOption parameter. If no open options are specified, and the file does not exist, a new file is created.


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

    }
}

How to Read and Write Text File in Java, Step 1 : Create a File object by passing the path of the file to be modified. Step 2 : Initialize oldContent with an empty string. This String object will hold all the old content of the input text file. Step 3 : Create BufferedReader object to read the input text file line by line. The write() method takes path of the given file, the text to the written and how the file should be open for writing. In our case, we used APPEND option for writing. Since the write() method may return an IOException , we use a try-catch block to catch the exception properly.


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.

java, Useful Java code examples for reading and writing text files. It also creates a new file if not exits, or overwrites the existing one. If you want to  Hello there, here is some text. We are writing the text to the file. Writing Binary Files in Java. You can create and write to a binary file in Java using much the same techniques that we used to read binary files, except that we need FileOutputStream instead of FileInputStream. In the following example we write out some text as binary data to the file.


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

Java - Edit File Example, Modify File java, I have seen many people struggling with Reading files and writing files in java, So in this code snippet I have put all these problems into one small program appened all text read in from the file to a string buffer which will be used to edit Create, edit, modify multiple text files using c++ · Member Avatar  I haven't done this in Java recently, but writing an entire file into memory seems like a bad idea. The best idea that I can come up with is open a temporary file in writing mode at the same time, and for each line, read it, modify if necessary, then write into the temporary file. At the end, delete the original and rename the temporary file.


edit « text file « Java I/O Q&A, write() method is used to create file and write the content in file. To edit file in java we need to search text which replace with new text. indexOf() method will search text in java and append() method will modify old content in string. I would like to add a bit more to MadProgrammer's Answer. In case of multiple line writing, when executing the command . writer.write(string); one may notice that the newline characters are omitted or skipped in the written file even though they appear during debugging or if the same text is printed onto the terminal with,


Java, i think i can use "Scanner" to read a .txt file but how can i write or even create a new text file? 4. In java, how do i edit 1 line of a text file? stackoverflow.com. Ok so I know the value As in your other thread, please only one thread per question. 5. Java Writing to Text File Example. In the following example, a FileWriter is used to write two words “Hello World” and “Good Bye!” to a file named MyFile.txt: package net.codejava.io; import java.io.FileWriter; import java.io.IOException; /** * This program demonstrates how to write characters to a text file.


Reading and Writing Files in Java, The many ways to write data to File using Java. Let's start simple – and use BufferedWriter to write a String to a new file: We can create the writer using FileWriter, BufferedWriter or even System.out. Let's now illustrate how to write and edit inside an existing file – rather than just writing to a completely  In Java, creating a file is easy by using pre-defined classes and packages. There are three ways to create a file. The File.createNewFile () is a method of File class which belongs to a java.io package. It does not accept any argument. The method automatically creates a new, empty file. The method returns a boolean value: