【问题标题】:Write in a specific line from txt in Java在 Java 中的 txt 中写入特定行
【发布时间】:2015-08-20 10:18:49
【问题描述】:

这是我的代码:

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

}

基本上我想在检测到条件时替换特定行。 我知道要更改哪条线,但我不知道如何替换它。因为目前我只能检测一行的开头并更改当前行而不是前一行。

我尝试使用 FileUtils.writeStringToFile 但它不起作用所以我在这里寻求帮助:(

谢谢大家!

编辑:我的输入是这样的:

{
      "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"
      }
    }

我实际上正在做的是当我找到“名称”行时:“CAREQUEIRANNE”,我想替换他的颜色属性,所以我必须去当前行 - 3,我真的不知道该怎么做它

编辑 2:

我的方法是这样调用的:

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

当我发现我的 Pattern 与文件中的研究相匹配时,我调用我的函数来替换一个城市的颜色属性

编辑 3:

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

}

【问题讨论】:

  • 我使用 java 7 和 Commons IO 库
  • 您能否展示一个输入示例、程序给出的输出以及您期望它的样子?
  • 确定我已经编辑了我的帖子
  • 方法怎么调用?
  • 为什么不直接解析 JSON 输入,修改你的单个值,然后将修改后的 JSON 重新保存到文件中?

标签: java


【解决方案1】:

您需要使用队列(缓冲区)在 Java 中临时保存文件的一小段,以便您检测何时并允许您更改相应的行。

与其写出该行,不如立即将该行推入队列(缓冲区)并从队列中弹出下一个项目。如果刚刚弹出的是要更改的,则将修改后的行写入文件,否则将原始行写入文件。

一些糟糕的伪代码来帮助表达这个想法。

// 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

【讨论】:

  • 不幸的是,我不想在一个循环中这样做:“每次我看到 myPattern[i] == arrayCity[i] 然后用我的 BufferedWriter 替换 n-3 行”(用n 当前行数)所以我无法将文件的开头推入队列:/
  • @Kyouma78 您可以创建自己的缓冲区,其中包含 3 行,如滑动窗口,当您转到下一行时,您可以编写第 n-4 行 ...
  • 仔细考虑一下。您不会在前三行中看到匹配的行。这些可以一次安全地读取一个并推送到队列中。您可能需要提供保护措施以防止短文件,但这应该有效。
  • 我建议的队列是我的滑动窗口。它最多只能包含三行。
  • @BrettWalker 只是试图澄清当你到达n 行时,写n-4 行是安全的,它不会改变。 (+1)
猜你喜欢
  • 2014-11-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 2018-12-28
  • 1970-01-01
  • 2014-06-03
  • 1970-01-01
相关资源
最近更新 更多