How to read a single word (or line) from a text file Java?

后端 未结 4 2115
不思量自难忘°
不思量自难忘° 2021-01-13 13:25

Like the title says, im trying to write a program that can read individual words from a text file and store them to String variables. I know how to use a

4条回答
  •  既然无缘
    2021-01-13 13:53

    To read lines from a text file, you can use this (uses try-with-resources):

    String line;
    
    try (
        InputStream fis = new FileInputStream("the_file_name");
        InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
        BufferedReader br = new BufferedReader(isr);
    ) {
        while ((line = br.readLine()) != null) {
            // Do your thing with line
        }
    }
    

    More compact, less-readable version of the same thing:

    String line;
    
    try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("the_file_name"), Charset.forName("UTF-8")))) {
        while ((line = br.readLine()) != null) {
            // Do your thing with line
        }
    }
    

    To chunk a line into individual words, you can use String.split:

    while ((line = br.readLine()) != null) {
        String[] words = line.split(" ");
        // Now you have a String array containing each word in the current line
    }
    

提交回复
热议问题