Read all lines with BufferedReader

后端 未结 7 699
醉梦人生
醉梦人生 2020-12-08 14:24

I want to type a multiple line text into the console using a BufferedReader and when I hit \"Enter\" to find the sum of the length of the whole text. The problem is that it

7条回答
  •  失恋的感觉
    2020-12-08 15:04

    Put every lines into String[] array. and second method get the number of lines contains in text file. I hope this might be useful to anyone..

    public static void main(String... args) throws IOException {
        String[] data = getLines();
        for(String v : data) {
            out.println(v);
        }
    }
    
    public static String[] getLines() throws IOException {
        BufferedReader bufferReader = new BufferedReader(new FileReader("C:\\testing.txt"));
        String line = bufferReader.readLine(); 
        String[] data = new String[getLinesLength()];
        int i = 0;
        while(line != null) {
            data[i] = line; 
            line = bufferReader.readLine();
            i++;
        }
        bufferReader.close();
        return data;
    }
    
    public static int getLinesLength() throws IOException {
        BufferedReader bufferReader = new BufferedReader(new FileReader("C:\\testing.txt"));
        String line = bufferReader.readLine(); 
        int size = 0;
        while(line != null) {
            size += 1;
            line = bufferReader.readLine();
        }
        bufferReader.close();
        return size;
    }
    

提交回复
热议问题