0

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

}

5
  • I use java 7 and Commons IO library Commented Jun 5, 2015 at 12:55
  • Can you show an example of the input, the output your program gives, and what you expected it to look like? Commented Jun 5, 2015 at 13:00
  • how do you call the method? Commented Jun 5, 2015 at 13:09
  • Why not just parse the JSON input, modify your single value, and then resave the modified JSON in the file? Commented Jun 5, 2015 at 14:28
  • Because i don't want to modify only 1 field, indeed there is a big file in JSON and i want to replace the color attribute of each city automatically Commented Jun 5, 2015 at 14:30

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

14 Comments

Unfortunately i wan't to do that in a loop like : "each time i see that myPattern[i] == arrayCity[i] then replace the n-3 line by my BufferedWriter" (with n the current number of line) so i can't push the beggining of my file into a queue :/
@Kyouma78 you could just create your own buffer holding 3 lines like a sliding window and when you go to the next line you can write line n-4...
Think carefully about this. You wont see a matching line in the first three lines. These can be safely read one at a time and pushed on to the queue. You may need to provide safeguard to protect against short files but this should work.
The queue I'm suggesting is my sliding window. It should only hold at most three lines.
@BrettWalker just tried to clarify that when you reach line n then it is safe to write line n-4, it won't change. (+1)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.