尝试从文件创建数组



我正在尝试将我在程序中制作的.txt文件中的每一行都放入数组中的每个框中。我想这样做的原因是,我可以在文件的每一行中搜索一个单词,然后打印整行。.txt文件的格式如下:鸟,, 位置, 日期因为当观察鸟时。我想做的第一件事是能够搜索一只鸟,然后打印整行,在另一种方法中,我希望能够做同样的事情,但搜索位置。目前我有一些可怕的东西根本不起作用,我真的可以使用一些帮助。

  void fugleType () {
System.out.println("Find observation by bird");
    List "fugler.txt" lines = new ArrayList<String>();
BufferedReader reader = null;
try {
    reader = new BufferedReader(new FileReader("fugler.txt"));
    String line = null;
    while ((line = reader.readLine()) != null) {
        lines.add(line);
    }
} finally {
    reader.close();
}
String[] array = lines.toArray();
 }

}`

你在那里有一些语法错误,最后你试图将数组列表转换为字符串数组。 以下是一些有效的代码,减去转换为数组,我将很快讨论。

public void fugleType () 
    {
        System.out.println("Find observation by bird");
        ArrayList<String> lines = new ArrayList<String>();
        BufferedReader reader = null;
        try 
        {
            reader = new BufferedReader(new FileReader("fugler.txt"));
            String line = null;
            while ((line = reader.readLine()) != null) 
            {
                lines.add(line);
            }
            reader.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

如果你真的需要把它转换为字符串数组,你必须遍历数组列表并将每个元素添加到字符串数组中。 这很简单,如果您想查看该代码,请告诉我。 Howerver,你已经有一个数组列表,你可以对它执行搜索操作。 为什么不直接使用它呢?

最新更新