Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

Modify the content of a file using Java

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();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...