简体   繁体   English

用Java从txt写入特定行

[英]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 :( 我试图使用FileUtils.writeStringToFile,但是它不起作用,所以我在这里寻求帮助:(

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 我实际上在做的是当我找到“名称”行:“ CAREQUEIRANNE”时,我想替换他的color属性,所以我必须转到当前行-3,而我真的不知道该怎么做

Edit 2 : 编辑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 : 编辑3:

@BrettWalker here is the new code : @BrettWalker这是新代码:

 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. 您需要使用队列(缓冲区)在Java中临时保存文件的一小段,以允许您检测时间并允许更改相应的行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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