简体   繁体   中英

Write in a specific line from txt in Java

Here is my code :

public static void modif(String name, String color, int k)
    {
        try {
        File input= new File("file1.txt");
        File output= new File("temp.txt");

        String correctLine = (String) FileUtils.readLines(input).get(k-3);

        BufferedReader br = new BufferedReader(new FileReader(input));
        BufferedWriter bw = new BufferedWriter(new FileWriter(output));
        String line="";


        while ((ligne = br.readLine()) != null){

            String lineConcat = line  + "\n";

         if(ligne.startsWith("\""+name+"\"")){

         System.out.println(correctLine); // i can display the line to change

             bw.write("\"" + name + "\"" + ": " + "\"" + color + "\"" + "\n"); // this is the way i replace my line
             System.out.println("Awesome !");
             bw.flush();
         }else{
             bw.write(lineConcat);
             bw.flush();
         }
        }
        bw.close();
        br.close();

        output.renameTo(new File("file2.txt"));

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

}

Basically i want to replace a specific line when a condition is detected. I know which line is to change but i don't know how to replace it. Because for now i can only detect the beggining of a line and change the current line not a previous one.

I tried to use FileUtils.writeStringToFile but it's not working so i'm here for help :(

Thanks guys !

Edit : my input is like that :

 { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [ [ 6.07721374522497, 43.08716485432151 ], [ 6.051202617426629, 43.07969629888752 ], [ 6.032563261594762, 43.07758570385911 ] ] ] }, "properties": { "_storage_options": { "color": "Orange" }, "name": "CARQUEIRANNE" } } 

What i'm doing actually is when i found the line "name": "CAREQUEIRANNE", i want to replace his color attribute so i have to go the current line - 3 and i really don't know how to do it

Edit 2 :

My method is called like that :

  BufferedReader in2 = new BufferedReader(new FileReader("file1.txt")); String line; String lineConcat = null; int k=1; while ((line = in2.readLine()) != null) { lineConcat = line + "\\n"; String myPattern = tabCity[21]; Pattern p = Pattern.compile(myPattern); Matcher m = p.matcher(lineConcat); //Matcher m2 = p2.matcher(lineConcat); if (m.find()){ System.out.println("Found !"); System.out.println(k); modif("color", "Orange", k); } else { System.out.println("Not Found"); } k++; } in2.close(); 

When i found that my Pattern matched with research in file, i call my function to replace the color attribute of a city

Edit 3 :

@BrettWalker here is the new code :

 public static void modif(String nom, String color, int k) { try { File input = new File("file1.txt"); File output = new File("temp.txt"); BufferedReader br = new BufferedReader(new FileReader(input)); BufferedWriter bw = new BufferedWriter(new FileWriter(output)); String line=""; Stack st = new Stack(); st.push(br.readLine()); st.push(br.readLine()); st.push(br.readLine()); while ((ligne = br.readLine()) != null){ String ligneConcat = ligne + "\\n"; st.push(ligneConcat); String oldLine = (String) st.pop(); if(ligne.startsWith("\\""+nom+"\\"")){ oldLine = "\\"" + nom + "\\"" + ": " + "\\"" + color + "\\"" + "\\n"; } bw.write(oldLine); } bw.write((int) st.pop()); bw.write((int) st.pop()); bw.write((int) st.pop()); bw.close(); br.close(); output.renameTo(new File("file2.txt")); } catch (IOException e) { e.printStackTrace(); } } 

You need to use a queue (buffer) to temporarily hold a small segment of the file in Java to allow you to detect when and allow you to change the appropriate line.

Instead of writing out the line immediately push the line onto a queue (buffer) and pop off the next item from the queue. If the one just popped of is the one to change then write the modified line to the file otherwise write the original line to the file.

A bit of poor pseudo code to help express the idea.

// Open up the readers/writers

// Prime the queue with the first few line of the file.
// Need to add safeguard to protect against small files!!
queue.push(br.readLine());
queue.push(br.readLine());
queue.push(br.readLine());

while ((line = br.readLine()) != null) {
    String lineConcat = line  + "\n";

    queue.push(lineConcat);

    String oldLine = queue.pop();

    if (line.startsWith("\""+name+"\"")) {
         oldLine = < Modify oldLine >
    }

    bw.write(oldLine)
}

// Empty the queue
bw.write(queue.pop());
bw.write(queue.pop());
bw.write(queue.pop());

// Close the readers/writer

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