在Java中搜索已保存的数据文件

时间:2018-01-05 17:55:23

标签: java search

我正在用Java创建一个图书馆系统,我可以添加新书,查看和保存它们。但是,我现在想要使用“搜索”窗口框搜索它们。保存的数据位于txt文件中。我想搜索特定的字段。我正在考虑实现线性搜索方法,但我不太清楚如何去做。

package bcu.storer;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import bcu.model.Book;


public class BookStorer {

public void StoreBooks(ArrayList<Book> booksList) throws IOException
{

    FileWriter fw = new FileWriter(".\\data\\books.txt");
    BufferedWriter bw = new BufferedWriter(fw);

    try {

    for (int i = 0; i < booksList.size(); i++)
    {
        String content = "";
        Book book = booksList.get(i);
        content += book.getIsbn()+"::";
        content += book.getTitle()+"::";
        content += book.getAuthor()+"::";
        content += book.getPublisher()+"::";
        content += book.getPudDate()+"::";
        content += book.getStatus()+"\n";


        bw.write(content);
    }
    System.out.println("Complete storing all books!");

    } catch (IOException ae) {

        ae.printStackTrace();

    } finally {

          try {

              if (bw != null)
                   bw.close();

              if (fw != null)
                   fw.close();

          } catch (IOException ex) {

              ex.printStackTrace();
          }


    }
}

}

这是将图书信息存储到TXT文件的代码,我想在搜索结果中访问这些数据。

2 个答案:

答案 0 :(得分:0)

这将逐行读取文件,并获得符合搜索条件的所有行。

此地图提供Book对象中每个字段的位置(列)。

private static Map<String, Integer> fieldToPositionMap = ImmutableMap.<String, Integer>builder()
                .put("Isbn", 0)
                .put("Title", 1)
                .put("Author", 2)
                .put("Publisher", 3)
                .put("PudDate", 4)
                .put("Status", 5)      
                .build();

注意:我使用GoogleGuava ImmutableMap构建地图,但您可以用传统方式构建地图。

搜索方法采用字段名称和要搜索的值(例如,Isbn = ABC或Publisher = XYZ)并返回符合条件的所有行(作为Book对象)。

public List<Book> search(String fieldName, String fieldValue) {
    try {
        return Files.lines(Paths.get("/path/to/txt/file")) //reads a file line by line
                .filter(line -> {
                    String[] blocks = line.split("::");
                    //filter (choose) a row if value of the searched field equals the provided value
                    return blocks[fieldToPositionMap.get(fieldName)].equals(fieldValue);
                })
                .map(this::deserialize) //convert the line to a Book object
                .collect(Collectors.toList()); //collect the result
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
//To convert a row from the file to a Book instance
private Book deserialize(String line) {
    String [] blocks = line.split("::");
    Book book = new Book();
    book.setIsbn(blocks[0]);
    book.setTitle(blocks[1]);
    book.setAuthor(blocks[2]);
    book.setPublisher(blocks[3]);
    book.setPudDate(blocks[4]);
    book.setStaus(blocks[5]);
}
Note: You might have to handle cases when a row does not have all fields

答案 1 :(得分:0)

我不确定这是不是你想要的。我帮助你。

 import java.io.BufferedReader;
 import java.io.FileReader;
 import java.io.IOException;

public class ReadFromFile {

  private static final String FILENAME = "pathToFile";

    public static void main(String[] args) {

    BufferedReader br = null;
    FileReader fr = null;

    try {

        //br = new BufferedReader(new FileReader(FILENAME));
        fr = new FileReader(FILENAME);
        br = new BufferedReader(fr);

        String sCurrentLine;

        while ((sCurrentLine = br.readLine()) != null) {
            Array[String] tmpBook = sCurrentLine.split("::");
            Book myBook = new Book(tmpBook(0),tmpBook(1),tmpBook(2), tmpBook(3), tmpBook(4), tmpBook(5))
            /*Check here if is the book you are looking for*/
        }

    } catch (IOException e) {

        e.printStackTrace();

    } finally {

        try {

            if (br != null)
                br.close();

            if (fr != null)
                fr.close();

        } catch (IOException ex) {

            ex.printStackTrace();

        }

    }

}

}

相关问题