Modify the content of a file using Java

2019-01-11 21:26发布

问题:

I want to delete some content of file using java program as below. Is this the write method to replace in the same file or it should be copied to the another file.

But its deleting the all content of the file.

class FileReplace
{
    ArrayList<String> lines = new ArrayList<String>();
    String line = null;
    public void  doIt()
    {
        try
        {
            File f1 = new File("d:/new folder/t1.htm");
            FileReader fr = new FileReader(f1);
            BufferedReader br = new BufferedReader(fr);
            while (line = br.readLine() != null)
            {
                if (line.contains("java"))
                    line = line.replace("java", " ");
                lines.add(line);
            }
            FileWriter fw = new FileWriter(f1);
            BufferedWriter out = new BufferedWriter(fw);
            out.write(lines.toString());
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
    public statc void main(String args[])
    {
        FileReplace fr = new FileReplace();
        fr.doIt();
    }
}

回答1:

I would start with closing reader, and flushing writer:

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

    public void  doIt() {
        try {
            File f1 = new File("d:/new folder/t1.htm");
            FileReader fr = new FileReader(f1);
            BufferedReader br = new BufferedReader(fr);
            while ((line = br.readLine()) != null) {
                if (line.contains("java"))
                    line = line.replace("java", " ");
                lines.add(line);
            }
            fr.close();
            br.close();

            FileWriter fw = new FileWriter(f1);
            BufferedWriter out = new BufferedWriter(fw);
            for(String s : lines)
                 out.write(s);
            out.flush();
            out.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String args[]) {
        FileReplace fr = new FileReplace();
        fr.doIt();
    }
}


回答2:

The accepted answer is great. However, there is an easier way to replace content in a file using Apache's commons-io library (commons-io-2.4.jar - you can use any latest versions)

private void update() throws IOException{
        File file = new File("myPath/myFile.txt");
        String fileContext = FileUtils.readFileToString(file);
        fileContext = fileContext.replaceAll("_PLACEHOLDER_", "VALUE-TO-BE-REPLACED");
        FileUtils.write(file, fileContext);
 }

Note: Thrown IOException needs to be caught and handled by the application accordingly.



回答3:

Read + write to the same file simulatenously is not ok.

EDIT: to rephrase and be more correct and specific - reading and writing to the same file, in the same thread, without properly closing the reader (and flusing the writer) is not ok.



回答4:

Make sure to:

  • close any stream when you no longer need them
  • In particular before reopening it for writing.
  • truncate the file, to make sure it shrinks if you write less than it had.
  • then write the output
  • write individual lines, don't rely on toString.
  • flush and close when you are finished writing!

If you use buffered IO, you always have to ensure that the buffer is flushed at the end, or you might lose data!



回答5:

I can see three problems.

First you are writing to out which I assume is System.out, not an output stream to the file.

Second, if you do write to an output stream to the file, you need to close it.

Third, the toString() method on an ArrayList isn't going to write the file like you are expecting. Loop over the list and write each String one at a time. Ask yourself whether you need to write newline characters as well.



回答6:

The accepted answer is slightly wrong. Here's the correct code.

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

public void  doIt() {
    try {
        File f1 = new File("d:/new folder/t1.htm");
        FileReader fr = new FileReader(f1);
        BufferedReader br = new BufferedReader(fr);
        while ((line = br.readLine()) != null) {
            if (line.contains("java"))
                line = line.replace("java", " ");
            lines.add(line);
        }
        fr.close();
        br.close();

        FileWriter fw = new FileWriter(f1);
        BufferedWriter out = new BufferedWriter(fw);
        for(String s : lines)
             out.write(s);
        out.flush();
                } 
        out.close();
   catch (Exception ex) {
        ex.printStackTrace();
    }
}