【问题标题】:Reading a desired line in a txt file在 txt 文件中读取所需的行
【发布时间】:2013-03-10 21:55:02
【问题描述】:

如何在我附加到的文本文件中搜索特定条目?

我制作了一个 GUI 来输入数据,但是我可以读取整个文件,但这对我没有用,因为我从用户的角度考虑,如果想要调用更早的预订,我就是对如何做到这一点的理解一无所知。当我读回数据时,我正在尝试实例化一个对象。

这是我的一些代码:

search.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            String booking;
            String where;
            booking = JOptionPane.showInputDialog(" Booking Reference: ");    
            System.out.println("Booking Reference " + e.getActionCommand());
            if (booking.equals("Wales"))
            try{

            FileInputStream fstream = new FileInputStream("Wales.txt");
            // Use DataInputStream to read binary NOT text.
            BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
            String strLine;

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

            System.out.println (strLine);
           }

            in.close();
            }
            catch (Exception ex)
            {
            System.err.println("Error: " + ex.getMessage());
            }
            else if (booking.equals("Scotland"))
            try{

            FileInputStream fstream = new FileInputStream("Scotland.txt");

            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine; 
            while ((strLine = br.readLine()) != null)   {

            System.out.println (strLine);
           }
            where = JOptionPane.showInputDialog("Which booking reference do you wish to search?: ");

            }
            catch (Exception ex)
            {
            System.err.println("Error: " + ex.getMessage());
            }
        }
    });

【问题讨论】:

  • 你不能用一些数据库代替吗?
  • 最终是的,这在待办事项清单上,但我想先尝试这种方式。
  • 你想要的线条是什么样子的?
  • 顺便说一句:首先做一些基本的事情,然后用 The Right Thing (TM) 替换它的正确方法是定义一个接口并隐藏它背后的基本代码。这样您就不必重写整个混乱,而只需替换接口的实现。

标签: java file-io


【解决方案1】:

我认为您最好探索一种文件格式,例如 XML、JSON 或 INI 来处理这种事情。正如您开始意识到的那样,没有支持格式的文本文件就是:文本文件。

如果您只想读回一些键/值对,请尝试使用 INI 文件之类的内容,使用 this Java INI library

如果你想从一个保存的文件中实例化一个对象,XML 是一个更好的选择。将对象保存到文本文件,并从保存的文件中重构该对象称为Serialization

【讨论】:

  • 好的,然后看看序列化
猜你喜欢
  • 1970-01-01
  • 2011-08-20
  • 2018-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-15
相关资源
最近更新 更多