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

后端 未结 4 2089
不思量自难忘°
不思量自难忘° 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:55

    You must use StringTokenizer! here an example and read this String Tokenizer

    private BufferedReader innerReader; 
    public void loadFile(Reader reader)
            throws IOException {
        if(reader == null)
        {
            throw new IllegalArgumentException("Reader not valid!");
        }
            this.innerReader = new BufferedReader(reader);
        String line;
        try
        {
        while((line = innerReader.readLine()) != null)
        {
            if (line == null || line.trim().isEmpty())
                throw new IllegalArgumentException(
                        "line empty");
            //StringTokenizer use delimiter for split string
            StringTokenizer tokenizer = new StringTokenizer(line, ","); //delimiter is ","
            if (tokenizer.countTokens() < 4)
                throw new IllegalArgumentException(
                        "Token number not valid (<= 4)");
            //You can change the delimiter if necessary, string example
            /*
            Hello / bye , hi
            */
            //reads up "/"
            String hello = tokenizer.nextToken("/").trim();
            //reads up ","
            String bye = tokenizer.nextToken(",").trim();
            //reads up to end of line
            String hi = tokenizer.nextToken("\n\r").trim();
            //if you have to read but do not know if there will be a next token do this
            while(tokenizer.hasMoreTokens())
            {
              String mayBe = tokenizer.nextToken(".");
            }
        }
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }
    

提交回复
热议问题