【问题标题】:Read from a file that contains both int and string using bufferedReader使用 bufferedReader 从包含 int 和 string 的文件中读取
【发布时间】:2018-01-21 20:56:56
【问题描述】:

所以我试图读取一个包含 int 和 string 的文件。因此,主要目标是让用户输入参考编号,然后程序吐出下面的行。我正在尝试使用线性搜索算法,这是文件:

 1<---Reference #
 The Adventures of Tom Sawyer<---Line to Spit out
 2
 Huckleberry Finn
 4
 The Sword in the Stone
 6
 Stuart Little
 10
 Treasure Island
 12
 The Secret Garden
 14
 Alice's Adventures in Wonderland
 20
 Twenty Thousand Leagues Under the Sea
 24
 Peter Pan
 26
 Charlotte's Web
 31
 A Little Princess
 32
 Little Women
 33
 Black Beauty
 35
 The Merry Adventures of Robin Hood
 40
 Robinson Crusoe
 46
 Anne of Green Gables
 50
 Little House in the Big Woods
 52
 Swiss Family Robinson
 54
 The Lion, the Witch and the Wardrobe
 56
 Heidi
 66
 A Winkle in Time
 100
 Mary Poppins

这是我目前拥有的代码:

   public class NewJFrame extends javax.swing.JFrame {

   ArrayList<Integer> colours = new ArrayList<Integer>();
   BufferedReader br = null;
/**
 * Creates new form NewJFrame
 */
public NewJFrame() {
    int word=0;

    try {
        br = new BufferedReader(new FileReader("Booklist.txt"));

        while ((word == br.read())){
            colours.add(word);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    initComponents();
}

static public Boolean linearSearch(ArrayList colours, String B) {
    for (int k = 0; k < A.length; k++) {
        if (A[k].equals(B)) {
            return true;
        }
    }
    return false;
}

对于初学者来说,如果你能帮助我至少正确阅读文件,那就太好了。

【问题讨论】:

  • 为什么使用Boolean 而不是boolean
  • 如果您使用的是BufferedReader,为什么不使用它为您提供方便的非常方便的readLine() 方法呢? --- 另外,您是否知道您正在调用的 read() 方法一次只返回一个 character?它不会读取多个数字并返回它们所代表的数字。

标签: java bufferedreader


【解决方案1】:

最简单的方法是使用地图。

Map<Integer,String> readFileasMap(String file) throws IOException{
    Map<Integer,String> map = new HashMap<>();
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;
    while((line = br.readLine()) != null){
        int number = Integer.parseInt(line);
        String text = br.readLine();
        map.put(number, text);
    }
    br.close();
    return map;
}

然后您可以使用map.get(index) 返回相应的行。
如果您想将其与列表一起保存,则该功能非常相似。

List<Integer> indexes;
List<String> titles;
void readFileasLists(String file) throws IOException{
    indexes = new ArrayList<>();
    titles = new ArrayList<>();
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;
    while((line = br.readLine()) != null){
        int number = Integer.parseInt(line);
        String text = br.readLine();
        indexes.add(number);
        titles.add(text);
    }
    br.close();
    return;
}   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-01
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    相关资源
    最近更新 更多