简体   繁体   中英

How can i remove a word/line and replace it with a new one in a txt file (Java)?

For example we have a .txt file:

Name smth

Year 2012

Copies 1

And I want to replace it with that:

Name smth

Year 2012

Copies 0

Using java.io.*.

Read your original text file line by line and separate them into string tokens delimited by spaces for output, then when the part you want replaced is found (as a string), replace the output to what you want it to be. Adding the false flag to the filewrite object ("filename.txt", false) will overwrite and not append to the file allowing you to replace the contents of the file.

this is the code to do that

try {

        String sCurrentLine;

        BufferedReader br = new BufferedReader(new FileReader("yourFolder/theinputfile.txt"));
                BufferedWriter bw = new BufferedWriter(new FileWriter("yourFolder/theinputfile.txt" , false));

        while ((sCurrentLine = br.readLine()) != null) {
            if(sCurrentLine.indexOf("Copies")>=0){
                 bw.write("Copies 0")
            }

            System.out.println(sCurrentLine);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            br.close()bw.close();

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

hopefully that help

Here is the code that does that. Let me know if you have any question.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.LinkedHashMap;
import java.util.Map;

public class Test2 {
    Map<String, String> someDataStructure = new LinkedHashMap<String, String>();
    File fileDir = new File("c:\\temp\\test.txt");

    public static void main(String[] args) {
        Test2 test = new Test2();
        try {
            test.readFileIntoADataStructure();
            test.writeFileFromADataStructure();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    private void readFileIntoADataStructure() throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(
                new FileInputStream(fileDir)));
        String line;
        while ((line = in.readLine()) != null) {
            if (line != null && !line.trim().isEmpty()) {
                String[] keyValue = line.split(" ");
                // Do you own index and null checks here this is just a sample
                someDataStructure.put(keyValue[0], keyValue[1]);
            }
        }
        in.close();
    }

    private void writeFileFromADataStructure() throws IOException {
        Writer out = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(fileDir)));
        for (String key : someDataStructure.keySet()) {
            // Apply whatever business logic you want to apply here
            myBusinessMethod(key);
            out.write(key + " " + someDataStructure.get(key) + "\n");
            out.append("\r\n");
            out.append("\r\n");
        }
        out.flush();
        out.close();
    }

    private String myBusinessMethod(String data) {
        if (data.equalsIgnoreCase("Copies")) {
            someDataStructure.put(data, "0");
        }
        return data;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM