Read a text file until EOL in Java

前端 未结 3 1126
萌比男神i
萌比男神i 2021-01-29 08:07

I am trying to read a text file which has -

hello James!
How are you today!

I want to read the each character in the string till i find EOL ch

相关标签:
3条回答
  • 2021-01-29 08:51

    You can use something like that:

    while((line=input.readLine())!=null) {
        // do something
    }
    

    If you want to read char by char, you can use this:

    int readedValue;
    while ((readedValue = reader.read()) != -1) {
        char ch = (char) readedValue;
        // do something
    }
    

    Here is an example (with a string instead a file) for your new problem:

    String line;
    int readedValue;
    String s = "hello James!\n\rHow are you today!";
    StringReader input = new StringReader(s);
    BufferedReader lineReader= new BufferedReader (input);
    
    while((line=lineReader.readLine())!=null) {
        StringReader input2 = new StringReader(line);
        BufferedReader charReader= new BufferedReader (input2);
        while((readedValue = charReader.read()) != -1) {
            char ch = (char) readedValue;
            System.out.print(ch);
        }
    }
    
    0 讨论(0)
  • 2021-01-29 08:56

    As people have noted, the readline() method reads to the next line separator, and returns the line with the separator removed. So your tests for '\n' and '\r' in line cannot possibly evaluate to true.

    But you can easily add an extra end-of-line when you output the line string1.

    1 - that is, unless you actually need to preserve the exact same end-of-line sequence characters as in the input stream.

    You ask:

    Instead of using readline(), Is there any way i can use buffer reader to read each character and print them?

    Yea, sure. The read() method returns either one character or -1 to indicate EOF. So:

        int ch = br.read();
        while (ch != -1) {
           System.out.print((char) ch);
           ch = br.read();
        }
    
    0 讨论(0)
  • 2021-01-29 09:00

    Your problem is about magic numbers.

    your while will enter into an infinite loop in the case charAt(21)!='\n' && charAt(22)!='\r'

    those two integers shall be increased inside the loop.

    charAt(i)!='\n' && charAt(i+1)!='\r'
    ::inside loop
      i++
    
    0 讨论(0)
提交回复
热议问题