java - 如何搜索值,然后在找到该值时修改文件中的当前值

标签 java file file-handling

比如说我有这个文件

enter image description here

我希望我的程序使用用户的输入来搜索标题和各自的作者,然后请求替换值。然后这些替换将更改文件中的当前值。

这是我当前的实现:

import java.io.*;
import javax.swing.*;

public class SecondChild4 extends SecondParent
{
    public void edit(String sFileName, String sFileName2)
    {
    try
    {
        sFileName2 = "Second.txt";
        File nfile2 = new File("Second.txt");
        File file2 = new File("TempSecond.txt");

        FileReader reader2 = new FileReader(sFileName2);
        BufferedReader br2 = new BufferedReader(reader2);
        FileWriter twriter2 = new FileWriter(file2);
        BufferedWriter tbw2 = new BufferedWriter(twriter2);

        String line2 = "";
        String edit2 = "";
        String btitle = JOptionPane.showInputDialog (null, "Title: ", "");
        String bauthor = JOptionPane.showInputDialog (null, "Author: ", "");
            //how to search if value was found from the file?
        String btitle1 = JOptionPane.showInputDialog (null, "Replace with title: ", "");
        String bauthor1 = JOptionPane.showInputDialog (null, "Replace with author: ", "");

        line2 = br2.readLine();
        while(line2 != null){
        if (line2 == null)
        {
        // End of File 
        tbw2.close();
        br2.close();
        }
        else if(what condition to put here?)
        {
        System.out.println("Search found");
        edit = line2.replaceAll(btitle, btitle1);
        edit2 = line2.replaceAll(bauthor, bauthor1);        
        tbw1.append(edit);
        tbw1.append(",");
        tbw1.append(edit2);
        tbw1.append("\n");
        tbw2.write(edit);
        tbw2.write("\t");
        tbw2.write(edit2);
        tbw2.newLine();
        tbw1.close();
        tbw2.close();
        br1.close();
        br2.close();
        }

        else{
        tbw1.append(line1);
        tbw1.append("\n");
        tbw2.write(line2);
        tbw2.newLine();
        tbw1.close();
        tbw2.close();
        br1.close();
        br2.close();
        }
    }
        file2.delete();
        file2.renameTo(nfile2);
    }

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

我制作了一个临时文件来存储修改后的值,然后删除旧文件并根据以前的文件名重命名该临时文件。在我编写的代码中,存在文件内容为空等问题(我也是将其保存在csv中,但没有将与此相关的代码放在这里。当涉及到csv时,只有上一个文件的第一行被获取重写为临时文件),该文件不会被删除和重命名。

我知道我的代码有很多错误。我对编程还很陌生。请帮助我:)

最佳答案

您可以通过创建一个book.properties文件来很好地做到这一点,例如

Title=Foo
Author=bar

Java 代码将类似于:

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class SecondChild4 {

    private InputStream inputStream;

    public static void main(String[] args) {

        SecondChild4 s = new SecondChild4();
        s.getPropValues();
    }

    public String getPropValues() {
        String result = "";
        try {
            Properties prop = new Properties();
            String propFileName = "book.properties";

            inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);

            if (inputStream != null) {
                prop.load(inputStream);
            } else {
                throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
            }

            // get the property value and print it out
            String title = prop.getProperty("Title");
            String author = prop.getProperty("Author");

            result = "Book = " + author + " title " + title;
            System.out.println("current book details are " + result);

            // replace logic here
            prop.setProperty("Title", "Hamlet");
            prop.setProperty("Author", "William Shakespeare");

            System.out.println("after modification");
            result = "Book = " + prop.getProperty("Author") + " title " + prop.getProperty("Title");
            System.out.println("cuurrent book details are " + result);
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return result;
    }
}

输出:

current book details are Book = bar title Foo after modification

current book details are Book = William Shakespeare title Hamlet

编码时需要记住的一些事情:

  1. 不要仅仅为了避免异常而将所有内容都放在 try catch block 中,只保留实际引发异常的部分......而不是整个代码。

  2. 在finally block 中调用所有close方法,例如:buffereader.close()

  3. 永远、永远、永远不要抛出异常,而是自己捕获异常。

关于java - 如何搜索值,然后在找到该值时修改文件中的当前值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31768772/

相关文章:

java - 无法扩展 android.widget.MediaController 来覆盖 setSystemUiVisibility

java - 如何在一个类中处理多个线程?

python - "OSError: telling position disabled by next() call"错误的含义?

go - 如何同时遍历 N 个文件以计算唯一单词的出现次数

c - 如何使用 C 中的 putw() 函数将整数写入文本文件?

java - Java中如何检查对象结果是否大于0

c# - 逐行比较两个文本文件

java - 检查字符串数组然后将其写入文件的最有效方法

c - 关于 printf 中的字符串

java - 如何替换字符串中的指定空格?