如何将其更改为数组?

时间:2018-12-07 21:10:40

标签: java arrays arraylist

我已经编写了这段代码,但是我必须将其从保存在列表中更改为保存在数组中。这样,我txt文件中的每个动物都应在数组中具有其位置。有10只动物。有人可以帮忙吗?

public class Main {

public static void main(String[] args) {

    String line = "";
    int count = 0;

    List<String> arrayList = new ArrayList<>();

    try {
        BufferedReader br = new BufferedReader(new FileReader("Zoo.txt"));
        while (line != null) {
            count++;
            line = br.readLine();
            if (line == null)
                break;
            if (count == 3 || count % 3 == 1 && !line.equals("1") && 
     !line.equals("5") && !line.equals("10"));
                arrayList.add(line);
        }
        System.out.println(Arrays.toString(arrayList.toArray()));

        br.close();

        } catch (FileNotFoundException e) {
        System.err.println("File not found.");
    }catch (IOException e) {
        System.err.println("Cannot read this file.");
    }

   }
}

2 个答案:

答案 0 :(得分:2)

使用Java8 +,您可以:

Path path = Paths.get("Zoo.txt");
String[] animals = Files.lines(path, Charset.defaultCharset()).toArray(String[]::new);

答案 1 :(得分:0)

基于@Ryan的建议:

public static void main(String[] args) {
    // TODO Auto-generated method stub
     String line = "";
        int count = 0;
        int countLineNumber=0; //to count line numbers 
        List<String> arrayList = new ArrayList();

        try {
            BufferedReader br = new BufferedReader(new FileReader("Zoo.txt"));
            while (line != null) {
                count++;
                line = br.readLine();
                if (line == null)
                    break;
                if (count == 3 || count % 3 == 1 && !line.equals("1") && 
         !line.equals("5") && !line.equals("10"));
                    arrayList.add(line);
                countLineNumber++;
            }
            //System.out.println(countLineNumber);

            br.close();

            } catch (FileNotFoundException e) {
            System.err.println("File not found.");
        }catch (IOException e) {
            System.err.println("Cannot read this file.");
        }

        //getting elements from arayList saving them into a array 
        String[] array=new String[countLineNumber];
        for(int i=0;i<countLineNumber;i++){
            array[i]=arrayList.get(i);
        }

        //display element in array
        for(int k=0;k<array.length;k++){
        System.out.println(array[k]);

        }
}